Created
January 15, 2019 19:03
-
-
Save concubicycle/b8aaaae4ddb6d8bd2d05bba0a1686cb1 to your computer and use it in GitHub Desktop.
Culture Info Find Test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Collections.Generic; | |
using System.Globalization; | |
using Newtonsoft.Json.Linq; | |
using BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Running; | |
public class Program | |
{ | |
public static void Main() | |
{ | |
var summary = BenchmarkRunner.Run<Test>(); | |
} | |
} | |
public class Test | |
{ | |
private Dictionary<string, CultureInfo> _cultures; | |
private string DefaultCulture = "en-US"; | |
[GlobalSetup] | |
public void Setup() | |
{ | |
_cultures = CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures) | |
.ToDictionary(c => c.Name, StringComparer.OrdinalIgnoreCase); | |
} | |
[Benchmark] | |
public CultureInfo TryCatch() | |
{ | |
return TryCatchFind("de-DE"); | |
} | |
[Benchmark] | |
public CultureInfo Find() | |
{ | |
return Find("de-DE"); | |
} | |
[Benchmark] | |
public CultureInfo TryCatchFail() | |
{ | |
return TryCatchFind("asdf"); | |
} | |
[Benchmark] | |
public CultureInfo FindFail() | |
{ | |
return Find("asdf"); | |
} | |
private CultureInfo Find(string cultureCode) | |
{ | |
if (!_cultures.ContainsKey(cultureCode)) | |
{ | |
return _cultures[cultureCode]; | |
} | |
return _cultures[cultureCode]; | |
} | |
private CultureInfo TryCatchFind(string cultureCode) | |
{ | |
try | |
{ | |
return CultureInfo.GetCultureInfo(cultureCode); | |
} | |
catch (CultureNotFoundException) | |
{ | |
if (cultureCode == null) | |
{ | |
return CultureInfo.CurrentCulture; | |
} | |
else | |
{ | |
try | |
{ | |
return CultureInfo.GetCultureInfo(DefaultCulture); | |
} | |
catch (CultureNotFoundException) | |
{ | |
return CultureInfo.CurrentCulture; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment