4

Possible Duplicate:
Array versus List<T>: When to use which?

Is there any best practice or rule of thumb when to use a list vs an array? For example, a tutorial I am following uses arrays to hold some data, and he is always saying "Oh an array of 40 will be enough because I am never going to use more than that.

However, I have swapped out his arrays for Lists. That way the size of the list can adjust to my needs at run time, and it also allows me to use the IEnumerable iterator so I can use for each loops.

So, is there any downsize to using a List? I am guessing its more of a performance hit than using arrays, but is it significant? Should I try and use Arrays more often or go with Lists and only use arrays if I notice a performance issue?

peterh
  • 11,875
  • 18
  • 85
  • 108
Terry
  • 842
  • 1
  • 11
  • 26

6 Answers6

5

Lists are usually the way to go, unless as you say, that you need to squeeze more performance:

and

When exposing lists to consumers, remember to pick an appropriate Interface (i.e. expose IList, ICollection or IEnumerable, not List<T>, depending on the minimum contract you wish to guarantee to the consumer), as per this discussion here: IList vs IEnumerable for Collections on Entities

Community
  • 1
  • 1
StuartLC
  • 104,537
  • 17
  • 209
  • 285
3

I'd recommend looking at this SO answer.

Community
  • 1
  • 1
Matthew Abbott
  • 60,571
  • 9
  • 104
  • 129
1

It really depends on your usage scenario. If you are creating a collection of fixed length, which won't change, then you can use an array. If you want a collection which can grow and shrink efficiently, use a List.

Your code should express its intent, rather than worry about such micro optimisations ahead of time. If there is a performance problem in your application, profile it and address the issues identified by profiling.

Note that in .net 3.5, arrays implement IEnumerable<T>, so you can foreach over them.

Winston Smith
  • 21,585
  • 10
  • 60
  • 75
1

1) use List when you are going to modify it (add,delete) items.

2) gereric List is type-safe so you cannot insert other type by mistake

of cause you can easy convet List to array or crerate List from array.

Arseny
  • 7,251
  • 4
  • 37
  • 52
0

The arrays are more useful while we are operating with some algorithms (search sort etc.), if we only store data the to do some operation on all items is better to use list.

0

Arrays must perform better on random access and lists are better performing when adding and deleting items from collections.

LostMohican
  • 3,082
  • 7
  • 29
  • 38