よく使うintから文字列への変換Performance測定
計測コード
[MemoryDiagnoser, RankColumn]
public class ScoreBoard
{
[Params(999999)]
public int score;
[Benchmark]
public string Case1()
{
return "Score : " + score.ToString();
}
[Benchmark]
public string Case2()
{
return "Score : " + score;
}
[Benchmark]
public string Case3()
{
string scoreText = score.ToString();
return string.Format("Score : {0}", scoreText);
}
[Benchmark]
public string Case4()
{
return string.Format("Score : {0}", score);
}
[Benchmark]
public string Case5()
{
return $"Score : {score}";
}
[Benchmark]
public string Case6()
{
string scoreText = score.ToString();
return $"Score : {scoreText}";
}
[Benchmark]
public string Case7()
{
string scoreText = score.ToString();
return ZString.Concat("Score : " + scoreText);
}
[Benchmark]
public string Case8()
{
return ZString.Concat("Score : ", score);
}
[Benchmark]
public string Case9()
{
string scoreText = score.ToString();
return ZString.Format("Score : {0}", scoreText);
}
[Benchmark]
public string Case10()
{
return ZString.Format("Score : {0}", score);
}
}
結果
//BenchmarkDotNet=v0.12.0, OS=Windows 10.0.18362
//Intel Core i5-9600K CPU 3.70GHz(Coffee Lake), 1 CPU, 6 logical and 6 physical cores
// [Host] : .NET Framework 4.8 (4.8.4121.0), X64 RyuJIT
// DefaultJob : .NET Framework 4.8 (4.8.4121.0), X64 RyuJIT
//| Method | score | Mean | Error | StdDev | Rank | Gen 0 | Gen 1 | Gen 2 | Allocated |
//|------- |------- |----------:|---------:|---------:|-----:|-------:|------:|------:|----------:|
//| Case1 | 999999 | 59.98 ns | 0.670 ns | 0.627 ns | 2 | 0.0204 | - | - | 96 B |
//| Case2 | 999999 | 60.23 ns | 0.331 ns | 0.310 ns | 2 | 0.0204 | - | - | 96 B |
//| Case3 | 999999 | 132.33 ns | 1.099 ns | 0.975 ns | 5 | 0.0203 | - | - | 96 B |
//| Case4 | 999999 | 139.31 ns | 1.503 ns | 1.406 ns | 6 | 0.0253 | - | - | 120 B |
//| Case5 | 999999 | 139.09 ns | 0.712 ns | 0.666 ns | 6 | 0.0253 | - | - | 120 B |
//| Case6 | 999999 | 61.18 ns | 0.730 ns | 0.683 ns | 2 | 0.0204 | - | - | 96 B |
//| Case7 | 999999 | 117.34 ns | 0.965 ns | 0.903 ns | 4 | 0.0323 | - | - | 152 B |
//| Case8 | 999999 | 51.19 ns | 0.522 ns | 0.488 ns | 1 | 0.0119 | - | - | 56 B |
//| Case9 | 999999 | 196.12 ns | 1.129 ns | 1.056 ns | 7 | 0.0203 | - | - | 96 B |
//| Case10 | 999999 | 108.29 ns | 0.723 ns | 0.676 ns | 3 | 0.0118 | - | - | 56 B |
ZStringが使えるならこれを使ったほうが一番パフォーマンスがいい。
無理なら
ToString() と +演算子の組み合わせ
ToString() と $ - 文字列補間がパフォーマンスが良い
文字列の変換数が増えるとパフォーマンスは変わってくるが...