diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/EmbeddedLanguages/VirtualChars/CSharpVirtualCharService.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/EmbeddedLanguages/VirtualChars/CSharpVirtualCharService.cs index 11f2d9ceff053..991dbfe11d3c8 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/EmbeddedLanguages/VirtualChars/CSharpVirtualCharService.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/EmbeddedLanguages/VirtualChars/CSharpVirtualCharService.cs @@ -23,6 +23,8 @@ internal class CSharpVirtualCharService : AbstractVirtualCharService { public static readonly IVirtualCharService Instance = new CSharpVirtualCharService(); + private static readonly ObjectPool.Builder> s_pooledBuilders = new(() => ImmutableSegmentedList.CreateBuilder()); + protected CSharpVirtualCharService() { } @@ -285,11 +287,20 @@ private static VirtualCharSequence CreateVirtualCharSequence( string tokenText, int offset, int startIndexInclusive, int endIndexExclusive, ArrayBuilder<(char ch, TextSpan span)> charResults) { // Second pass. Convert those characters to Runes. - var runeResults = ImmutableSegmentedList.CreateBuilder(); + using var pooledRuneResults = s_pooledBuilders.GetPooledObject(); + var runeResults = pooledRuneResults.Object; - ConvertCharactersToRunes(charResults, runeResults); + try + { + ConvertCharactersToRunes(charResults, runeResults); - return CreateVirtualCharSequence(tokenText, offset, startIndexInclusive, endIndexExclusive, runeResults); + return CreateVirtualCharSequence(tokenText, offset, startIndexInclusive, endIndexExclusive, runeResults); + } + finally + { + // Ensure the builder is cleared out before releasing back to the pool. + runeResults.Clear(); + } } private static void ConvertCharactersToRunes(ArrayBuilder<(char ch, TextSpan span)> charResults, ImmutableSegmentedList.Builder runeResults)