Skip to content

Commit e30d638

Browse files
authored
Slightly reduce allocations in SymbolCompletionItem.AddSymbolInfo (#76418)
* Slightly reduce allocations in SymbolCompletionItem.AddSymbolInfo This code creates a string from the SymbolKind enum and was showing up as 0.2% of allocations in the typing scenario in the csharp editing speedometer test. Instead, mimic what the core runtime does in the Number class by keeping a small cache mapping int => string that is lazily populated.
1 parent 2eca5b2 commit e30d638

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for more information.
4+
5+
namespace Microsoft.CodeAnalysis.Completion.Providers;
6+
7+
internal static class SmallNumberFormatter
8+
{
9+
private const int SmallNumberCacheLength = 32;
10+
11+
/// <summary>
12+
/// Lazily-populated cache of strings for values in the range [0, <see cref="SmallNumberFormatter"/>).
13+
/// Inspired by corresponding field in core runtime's Number class.
14+
/// </summary>
15+
private static readonly string[] s_smallNumberCache = new string[SmallNumberCacheLength];
16+
17+
internal static string ToString(int value)
18+
{
19+
if (value >= SmallNumberCacheLength)
20+
return value.ToString();
21+
22+
return s_smallNumberCache[value] ??= value.ToString();
23+
}
24+
}

src/Features/Core/Portable/Completion/Providers/SymbolCompletionItem.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ private static void AddSymbolInfo(ImmutableArray<ISymbol> symbols, ArrayBuilder<
8585
{
8686
var symbol = symbols[0];
8787
var isGeneric = symbol.GetArity() > 0;
88-
properties.Add(KeyValuePairUtil.Create("SymbolKind", ((int)symbol.Kind).ToString()));
88+
properties.Add(KeyValuePairUtil.Create("SymbolKind", SmallNumberFormatter.ToString((int)symbol.Kind)));
8989
properties.Add(KeyValuePairUtil.Create("SymbolName", symbol.Name));
9090

9191
if (isGeneric)

0 commit comments

Comments
 (0)