开发者

What are the benefits to using String[] over List<String>? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicates:

c# array vs generic list

开发者_运维百科 Array versus List<T>: When to use which?

I understand that there are several benefits of using List<>. However, I was wondering what benefits might still exist for using arrays.

Thanks.


You'll have a simple static structure to hold items rather than the overhead associated with a List (dynamic sizing, insertion logic, etc.).

In most cases though, those benefits are outweighed by the flexibility and adaptability of a List.


One thing arrays have over lists is covariance.

    class Person { /* ... */}

    class Employee : Person {/* ... */}

    void DoStuff(List<Person> people) {/* ... */}

    void DoStuff(Person[] people) {/* ... */}

    void Blarg()
    {
        List<Employee> employeeList = new List<Employee>();
        // ...
        DoStuff(employeeList); // this does not compile

        int employeeCount = 10;
        Employee[] employeeArray = new Employee[employeeCount];
        // ...
        DoStuff(employeeArray); // this compiles
    }


An array is simpler than a List, so there is less overhead. If you only need the capabilities of an array, there is no reason to use a List instead.

The array is the simplest form of collection, that most other collections use in some form. A List actually uses an array internally to hold it's items.

Whenever a language construct needs a light weight throw-away collection, it uses an array. For example this code:

string s = "Age = " + age.ToString() + ", sex = " + sex + ", location = " + location;

actually becomes this code behind the scene:

string s = String.Concat(new string[] {
  "Age = ",
  age.ToString(),
  ", sex = ",
  sex,
  ", location = ",
  location
});


I would only use an array if your collection is immutable.

Edit: Immutable in a sense that your collection will not grow or shrink.


Speed would be the main benefit, unless you start writing your own code to insert/remove items etc.

A List uses an array internally and just manages all of the things a list does for you internally.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜