Creating an array is slower than pushing parameters onto the evaluation stack. Performance-critical methods are not best implemented with params keywords.
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
class Program
{
static int GetProduct(params int[] values)
{
// Use params.
int result = 1;
foreach (int value in values)
{
result *= value;
}
return result;
}
static int GetProduct2(int value1, int value2, int value3)
{
return 1 * value1 * value2 * value3;
}
const int _max = 1000000;
static void Main()
{
// Version 1: use params method.
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
GetProduct(2, 2, 3);
}
s1.Stop();
// Version 2: use int arguments.
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
GetProduct2(2, 2, 3);
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
}
}
9.11 ns params
0.27 ns int, int, int