Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Reduce StreamWriter allocation (#44495)
* 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