It seemed to me that I would quickly realize that the console application worked so quickly.
It mainly uses all 3 methods (constructor, LINQ and foreach) to get CultureInfo from a string 10,000 times in a loop. For brevity, I deleted the stopwatch and console output.
string culture = "en-GB"; CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures); for (int i = 0; i < 10000; i++) { try { CultureInfo c = new CultureInfo(culture); } catch { } } for (int i = 0; i < 10000; i++) { CultureInfo c = cultures.FirstOrDefault((x) => x.Name == culture); } for (int i = 0; i < 10000; i++) { foreach (CultureInfo c in cultures) { if (c.Name == culture) break; } }
The results are as follows:
Try Catch: 00:00:00.0023860 LINQ: 00:00:00.0542459 ForEach: 00:00:00.0238937
If you delete a culture variable and call it each iteration, then LINQ and ForEach loops take about 2.5 seconds.
Thus, using the constructor is beneficial if you expect to get a lot of valid input and only an odd invalid. But if you change the value, if the input is from en-GB to TEST , then everything will change in bulk.
Invalid Culture Try Catch: 00:00:39.7163513 Invalid Culture LINQ: 00:00:00.0791752 Invalid Culture ForEach: 00:00:00.0291480
Obviously, my test application is not a real scenario, but since the OP said that it was called for each request, I can imagine that there is a lot of code to call this code in a large web application. It can be a negative or service vector, process the entire processor by sending a web server with requests that have an invalid culture parameter.
Bencr source share