関数から整数(int)を 2 つ返すとき、配列とタプルの速度差を調べる
int の配列を new するのと、タプルを生成するのとで速度に差が出るのか計測してみました。
using System; using System.Diagnostics; class Program { static int[] CreateArray(int a, int b) { return new[] { a, b }; } static Tuple<int, int> CreateTuple(int a, int b) { return Tuple.Create(a, b); } static void Test(int n) { Console.WriteLine($"n = {n}"); var sw = new Stopwatch(); sw.Start(); for (int i = 0; i < n; i++) { CreateArray(1, 2); } sw.Stop(); Console.WriteLine($"array: {sw.ElapsedMilliseconds}ms"); sw.Restart(); for (int i = 0; i < n; i++) { CreateTuple(1, 2); } sw.Stop(); Console.WriteLine($"tuple: {sw.ElapsedMilliseconds}ms"); Console.WriteLine(); } static void Main() { for (int i = 1; i < 10; i++) { Test((int)Math.Pow(10, i)); } } }
実行結果です。
n = 10 array: 0ms tuple: 0ms n = 100 array: 0ms tuple: 0ms n = 1000 array: 0ms tuple: 0ms n = 10000 array: 0ms tuple: 0ms n = 100000 array: 2ms tuple: 1ms n = 1000000 array: 10ms tuple: 10ms n = 10000000 array: 115ms tuple: 109ms n = 100000000 array: 1099ms tuple: 1031ms n = 1000000000 array: 11613ms tuple: 10352ms
手元の環境で上記のコードで計測する限りにおいては、速度に大きな差は見られませんでした。
環境
% mono --version Mono JIT compiler version 4.6.2 (Stable 4.6.2.16/ac9e222 Sat Jan 7 16:00:28 PST 2017) Copyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com