Problem with array performance. .List

Possible duplicate:
Array and List Performance

I want to know which one is best suited for 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 a performance issue? Or any other better way. Thanks.

+4
source share
3 answers

The first one will probably work better, but only a little. The reason is that, despite the presence of an array behind this list, iteration through the list must go through several levels of method calls in order to get the values, whereas the array is almost direct memory addressing. The difference will be so small that you will have to sort through thousands of times to measure it. This is called micro-optimization , and it is usually considered a waste of effort.

+7
source

If you always add the same to an array, use this syntax:

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

The array is more efficient; the list is likely to result in the actual resizing.

0
source

I want to know which one is the best way to accomplish this task.

As always in programming, people without knoledge are looking for a simple solution. There's nothing here. Look, there is a difference in performance, it does not matter for a given task (too little data).

In general, an array is faster, but has serious problems with other elements. ininsert / delete is slower since all elements must be copied to a new array.

The list does not have a copy problem, but each record is a node, which means much more memory usage and much more memory - each record is your object + node object with pointers back and forth to the next / last element. This makes random access slower, sometimes significantly. Not a problem if you ONLY do foreach, especially with 7 elements. This is much more if you have thousands of access to a list of 250,000 items.

Part of your programming training is understanding the standard features of EVERY element on the list. The above question is an entry-level beginner question - one that I like to use in a programmer's interview to get rid of wannabes.

0
source

Source: https://habr.com/ru/post/1389989/


All Articles