Skip to content

Commit 663a610

Browse files
ToddGrungithub-actions
authored andcommitted
Avoid allocations from calls to CultureInfo.GetCultures
A local profile taken during running the vsixinstaller on roslyn indicated this call was allocating quite heavily in the "devenv /updateconfiguration" process the vsixinstaller kicks off. DirectoryBasedTemplate.ParseLocFileName was allocating 8.1% of all allocations in that devenv process, nearly all of which comes from the CultureInfo.GetCultures call. Instead of allocating all cultures and an array to hold them by calling CultureInfo.GetCultures, this code can use CultureInfo.GetCultureInfo with the requested culture name and use that result instead. Note that GetCultureInfo throws if the requested culture name isn't supported, so we need to catch the corresponding CultureNotFoundException.
1 parent 089a47f commit 663a610

1 file changed

Lines changed: 7 additions & 2 deletions

File tree

src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/DirectoryBasedTemplate.cs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -142,9 +142,14 @@ internal Task ValidateAsync(ValidationScope scope, CancellationToken cancellatio
142142
{
143143
string filename = locFile.Name;
144144
string localeStr = filename.Substring(LocalizationFilePrefix.Length, filename.Length - LocalizationFilePrefix.Length - LocalizationFileExtension.Length);
145+
CultureInfo? locale = null;
145146

146-
CultureInfo? locale = CultureInfo.GetCultures(CultureTypes.AllCultures).FirstOrDefault(c => c.Name.Equals(localeStr, StringComparison.OrdinalIgnoreCase));
147-
if (locale == null)
147+
try
148+
{
149+
// PERF: Avoid calling CultureInfo.GetCultures and searching the results as it heavily allocates on each invocation.
150+
locale = CultureInfo.GetCultureInfo(localeStr);
151+
}
152+
catch (CultureNotFoundException)
148153
{
149154
Logger.LogWarning(LocalizableStrings.LocalizationModelDeserializer_Error_UnknownLocale, localeStr);
150155
}

0 commit comments

Comments
 (0)