パフォーマンス関連
実験君1
class Num
{
public static char utoa (ulong u)
{
char tmp = new char [20];
int i = tmp.Length;
do {
tmp [--i] = (char)(u % 10 + '0');
} while ((u /= 10) > 0);
char [] cs = new char [tmp.Length - i];
Array.Copy (tmp, i, cs, 0, cs.Length);
return cs;
}
}
実験君2
class Num { public static StringBuilder utoa (ulong u) { StringBuilder sb = new StringBuilder (20); do { sb.Insert (0, (char)(u % 10 + '0')); } while ((u /= 10) > 0); return sb; } }
実験君3
class Num { static ulong U = new ulong { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000, 100000000000, 1000000000000, 10000000000000, 100000000000000, 1000000000000000, 10000000000000000, 100000000000000000, 1000000000000000000, 10000000000000000000, }; public static char utoa (ulong u) { if (u == 0) return new char {'0'}; int i = 19, j = 0; while (u / U [i] == 0) --i; char [] cs = new char [i + 1]; do { ulong n = u / U [i]; cs [j++] = (char)(n + '0'); u -= U [i--] * n; } while (i >= 0); return cs; } }
これらを次のようなテストで比較。
class X { static void Main () { char[] cs; DateTime t; t = DateTime.Now; for (ulong i = 0; i < 1000000; ++i) cs = Num.utoa (1234567890); Console.WriteLine (DateTime.Now - t); } }
結果
n1:MS.NET - 00:00:00.7500000 n2:MS.NET - 00:00:01.6406250 n3:MS.NET - 00:00:01.3593750 n1:Mono - 00:00:02.1250000 (90019 KB) n2:Mono - 00:00:02.9530000 (76348 KB) n3:Mono - 00:00:01.9060000 (35332 KB)
全体的にMS.NETの方が速いですが、n1,n3の結果がMS.NETとMonoで逆転していることが気になりました。Monoはメモリアロケートが不利ってことなのかなぁ。