Skip to content

Commit

Permalink
Reduce StreamWriter allocation (#44495)
Browse files Browse the repository at this point in the history
* Lazily-allocate StreamWriter's byte[] buffer

The byte[] buffer is used just when flushing to the underlying stream, to store the intermediate bytes as generated from the characters by the encoding.  Currently the byte[] buffer is allocated in the constructor, but for relatively small strings written/flushed synchronously (such as those often used with Console.Write), we can avoid the buffer entirely via stack allocation (in Flush); for all other cases, we can allocate it on demand.

(I considered using ArrayPool to rent/return in each Flush{Async} call, but opted not to in this change.  Someone could investigate that subsequently.)

* Undo use of static async helpers

In .NET Framework, there was a non-trivial penalty due to StreamWriter deriving from MarshalByRefObject and the impact that had on async methods accessing lifted locals on the state machine (it made them significantly more expensive).  The workaround was to make the async methods be statics and pass in all of the relevant instance state needed.  That workaround is no longer necessary on core, where MarshalByRefObjects are nops, leaving behind a workaround that is not just clunkier, but actually makes things more expensive because more state needs to be stored on the state machine objects (all of the arguments, which can instead just be accessed off of `this`).  Undo that whole change.

* Address PR feedback
  • Loading branch information
stephentoub authored Nov 11, 2020
1 parent 035ebea commit 33c9d5a
Showing 1 changed file with 78 additions and 166 deletions.
Loading

0 comments on commit 33c9d5a

Please sign in to comment.