5

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.

Community
  • 1
  • 1
4b0
  • 21,981
  • 30
  • 95
  • 142
  • 3
    http://stackoverflow.com/questions/454916/performance-of-arrays-vs-lists – keyboardP Jan 09 '12 at 05:13
  • I think it depends on what you want to do. Array will be faster no matter what but Lists can be handy for certain tasks. I'd also recommend for your `List` to use `new List() { "Sunday", "Monday", "Tuesday" }` for initial values but that is just personal preference. Can also do with an array, `new [] { "Sunday", "Monday", "Tuesday" }`. – kamranicus Jan 09 '12 at 05:16

3 Answers3

9

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.

Chris Shain
  • 50,833
  • 6
  • 93
  • 125
0

If you're always putting the same things in the array, use this syntax:

String [] week = new String [] {
    "Sunday",
    "Monday",
    ...
};

The array is more efficient, the list will probably wind up resizing itself.

0

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

As always in programming, people without knoledge look for a simple solution. There is none. See, there IS a performance difference, it is totally irrelevant for rthe task given (too little data).

In general an array is faster but has serious issues with other elements -insert/delete is slow as all elements have to be copied to a new array.

List has no copy issue but every entry is a node that means a lot more memory use and a lot more memory acccess - every entry is your object + a node object with pointers back and forth to next / last element. This makes random access slower, sometimes significantly so. Not an issue if you ONLY do foreach, especially with only 7 elements. It is a lot more if you have thousands of accesses of a 250.000 item list.

Part of you learning programming is understanding the standard characteristics of EVERY item on the list. The above question is a trainee level beginner question - one I love using on programmer interviews to weed out the wannabes.

TomTom
  • 61,059
  • 10
  • 88
  • 148