Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array vs.list performance issue [duplicate]

Tags:

c#

asp.net

Possible Duplicate:
Performance of Arrays vs. Lists

I want to know which one is better way to do this task.

string[] week = new string[7]
  week[0] = "Sunday";
  week[1] = "Monday";
  week[2] = "Tuesday";

  foreach (string day in week)
   {
     //Some task
   }

and

List<string> week = new List<string>();
 list.Add("Sunday");
 list.Add("Monday");
 list.Add("Tuesday");

 foreach (string day in list) 
 {
    //Some Task
 }

Is there any performance issue?Or any other better way.Thanks.

like image 802
4b0 Avatar asked Jan 09 '12 05:01

4b0


1 Answers

The first one will probably perform better, but only ever so slightly. The reason is that even though there is an array behind that List, the iteration over the list has to go through a few more layers of method calls to get the values, whereas the array is almost direct memory addressing. The difference will be so small that you would have to iterate thousands of times to measure it. This is what is called micro-optimization, and it is generally considered a waste of effort.

like image 153
Chris Shain Avatar answered Oct 11 '22 18:10

Chris Shain