Return pooled arrays in Regex.Replace when no replacements (#44833)
authorStephen Toub <stoub@microsoft.com>
Tue, 17 Nov 2020 22:55:53 +0000 (17:55 -0500)
committerGitHub <noreply@github.com>
Tue, 17 Nov 2020 22:55:53 +0000 (17:55 -0500)
commitc8494fc66bb975e1044d8daa7f06012c1fd84656
treedc49cf46a0dff641c0d97ab731a4c00a25a8224c
parentef2a1878793e7e3fc3060396d3d2655ac53b1316
Return pooled arrays in Regex.Replace when no replacements (#44833)

When Regex.Replace doesn't actually need to replace anything, we're inadvertently not returning a previously rented ArrayPool array to the pool.  On repeated use, that drains the pool of the desired size, such that every attempt ends up allocating a new array, even if there are no replacements to be made.

The fix is to lazily rent from the pool.  This not only fixes the problem, but helps perf further by not taking the rental cost unless we actually need an array to store a replacement segment.
src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Match.cs
src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.Replace.cs
src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexReplacement.cs
src/libraries/System.Text.RegularExpressions/src/System/Text/SegmentStringBuilder.cs