Created
September 1, 2017 15:04
-
-
Save ufcpp/97aa029d7ed2aeb5883e66d0f4a42b6e to your computer and use it in GitHub Desktop.
utf8 boyer mooreとかでググる → string.IndexOf の性能に関するStackOverlfowが目に付く → Ordinal付けるかどうかで性能差すごいらしい? → 30倍違った…(今ここ)
This file contains hidden or 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 BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Running; | |
using System; | |
using System.Net.Http; | |
using System.Threading.Tasks; | |
/// <summary> | |
/// こんなの、常に Ordinal 付けるしかないじゃない… | |
/// (デフォルト動作が CurrentCulture なのつらい。) | |
/// | |
/// Method | Mean | Error | StdDev | Allocated | | |
/// ---------------------- |------------:|-----------:|-----------:|----------:| | |
/// CurrentCultureIndexOf | 16,411.8 us | 173.195 us | 135.219 us | 0 B | | |
/// OrdinalIndexOf | 552.2 us | 2.131 us | 1.889 us | 0 B | | |
/// </summary> | |
[MemoryDiagnoser] | |
public class IndexOfBenchmark | |
{ | |
string text; | |
string[] patterns; | |
[GlobalSetup] | |
public void Setup() | |
{ | |
text = LoadDataAsync().GetAwaiter().GetResult(); | |
async Task<string> LoadDataAsync() | |
{ | |
var c = new HttpClient(); | |
var res = await c.GetAsync("http://ufcpp.net/study/csharp/cheatsheet/ap_ver7/"); | |
return await res.Content.ReadAsStringAsync(); | |
} | |
patterns = new[] | |
{ | |
"C#", | |
"throw", | |
"new", | |
"演算子", | |
"タプル", | |
"なさそうなもじれつ", | |
"一番重要視しているのは生産性の高さで、書きやすさ、読みやすさなどが一番大事です。", | |
"<span", | |
" ", | |
}; | |
} | |
[Benchmark] | |
public int CurrentCultureIndexOf() | |
{ | |
var sum = 0; | |
foreach (var p in patterns) | |
sum += Count(text, p, StringComparison.CurrentCulture); | |
return sum; | |
} | |
[Benchmark] | |
public int OrdinalIndexOf() | |
{ | |
var sum = 0; | |
foreach (var p in patterns) | |
sum += Count(text, p, StringComparison.Ordinal); | |
return sum; | |
} | |
private static int Count(string text, string pattern, StringComparison comp) | |
{ | |
var count = 0; | |
var i = 0; | |
while (true) | |
{ | |
i = text.IndexOf(pattern, i, comp); | |
if (i < 0) return count; | |
count++; | |
i++; | |
} | |
} | |
} | |
public class Program | |
{ | |
static void Main() | |
{ | |
BenchmarkRunner.Run<IndexOfBenchmark>(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment