728x90
1. 개요
Array 간의 데이터 타입 변환을 수행하고 성능을 비교한다.
2. 비교할 구현 코드
- For loop
- Linq Select
- Array.ConvertAll
[Test]
public void TestConvertPerf()
{
PerfBenchmark bench = new PerfBenchmark("Convert Benchmark");
var intArr = RandomUtils.GenerateInt(500000);
int repSize = 1000;
bench.Start();
for (int i = 0; i < repSize; i++)
{
ToDoubleArray(intArr);
bench.SaveCheckpoint();
}
bench.Stop();
Console.WriteLine($"Avg, Std of for Loop: {bench.CalculateAverage()}, {bench.CalculateStandardDeviation()}");
bench.ClearCheckpoint();
bench.Start();
for (int i = 0; i < repSize; i++)
{
ToDoubleArray2(intArr);
bench.SaveCheckpoint();
}
bench.Stop();
Console.WriteLine($"Avg, Std of Linq Select: {bench.CalculateAverage()}, {bench.CalculateStandardDeviation()}");
bench.ClearCheckpoint();
bench.Start();
for (int i = 0; i < repSize; i++)
{
ToDoubleArray3(intArr);
bench.SaveCheckpoint();
}
bench.Stop();
Console.WriteLine($"Avg, Std of Array.ConvertAll: {bench.CalculateAverage()}, {bench.CalculateStandardDeviation()}");
}
public static double[] ToDoubleArray(int[] array)
{
double[] doubleArray = new double[array.Length];
for (int i = 0; i < array.Length; i++)
{
doubleArray[i] = array[i];
}
return doubleArray;
}
public static double[] ToDoubleArray2(int[] array)
{
return array.Select(arr => (double)arr).ToArray();
}
public static double[] ToDoubleArray3(this int[] array)
{
return Array.ConvertAll(array, (ii) => (double)ii);
}
3. 벤치 테스트 결과
성능상에 Array.ConvertAll이 For loop보다 근소하게 빠르며, Linq 의 함수는 역시 시간이 상당히 오래걸림.
728x90
728x90