Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: params keyword vs. list

What are the pro/cons of using the params keyword vs. a List as input to some c# function?

Mainly what are the performance considerations and other trade offs.

like image 802
Yaron Naveh Avatar asked Jan 22 '10 01:01

Yaron Naveh


2 Answers

The params keyword is syntactic sugar handled by the C# compiler. underneath the hood, it's actually turning

void Foo(params object[] a) { ... } Foo(1,2,"THREE"); 

into

void Foo(object[] a) { ... } Foo(new object[] { 1, 2, "THREE" }) 

From a performance perspective like you're asking about, the params call is simply faster because it is a bit faster to create an array than it is to create a List<>. There is no performance difference between the two snippets above.

like image 88
Jimmy Avatar answered Sep 19 '22 14:09

Jimmy


Personally I use params when writing functions that take a number of inputs provided by another programmer (for example String.Format), and IEnumerable when writing functions that take a list of data items provided by the computer (for example File.Write).

The performance implications are negligible. Worrying about the performance of a trivial thing like this is exactly what Donald Knuth was talking about in the famous "premature optimization is the root of all evil" quote.

That said, the asker seems to be fixated on it, so here you go:

Results for 10 million iterations:

params took 308 ms list took 879 ms 

From these results we can see that the params array is just over twice as fast. The simple fact that you can call either of these things Ten Million Times in under a second means that you're completely wasting your time by worrying about it. Use whatever suits your code the best.

The code to test it (compiled and run in release mode using VS2008)

class Program {     const int COUNT = 10000000;      static IEnumerable<string> m_value = null;      static void ParamsMethod(params string[] args)     { m_value = args; } // do something with it to stop the compiler just optimizing this method away      static void ListMethod(List<string> args)     { m_value = args; } // do SOMETHING with it to stop the compiler just optimizing this method away      static void Main(string[] args)     {         var s = new Stopwatch();         s.Start();         for (int i = 0; i < COUNT; ++i)             ParamsMethod("a", "b", "c");          Console.WriteLine("params took {0} ms", s.ElapsedMilliseconds);          s.Reset();         s.Start();         for (int i = 0; i < COUNT; ++i)             ListMethod(new List<string> { "a", "b", "c" });          Console.WriteLine("list took {0} ms", s.ElapsedMilliseconds);     } } 
like image 43
Orion Edwards Avatar answered Sep 20 '22 14:09

Orion Edwards