Skip to content

Commit

Permalink
Avoid allocations from calls to CultureInfo.GetCultures
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
ToddGrun authored and github-actions committed Jul 16, 2024
1 parent 089a47f commit 663a610
Showing 1 changed file with 7 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -142,9 +142,14 @@ internal Task ValidateAsync(ValidationScope scope, CancellationToken cancellatio
{
string filename = locFile.Name;
string localeStr = filename.Substring(LocalizationFilePrefix.Length, filename.Length - LocalizationFilePrefix.Length - LocalizationFileExtension.Length);
CultureInfo? locale = null;

CultureInfo? locale = CultureInfo.GetCultures(CultureTypes.AllCultures).FirstOrDefault(c => c.Name.Equals(localeStr, StringComparison.OrdinalIgnoreCase));
if (locale == null)
try
{
// PERF: Avoid calling CultureInfo.GetCultures and searching the results as it heavily allocates on each invocation.
locale = CultureInfo.GetCultureInfo(localeStr);
}
catch (CultureNotFoundException)
{
Logger.LogWarning(LocalizableStrings.LocalizationModelDeserializer_Error_UnknownLocale, localeStr);
}
Expand Down

0 comments on commit 663a610

Please sign in to comment.