Programing

배열 대 목록

lottogame 2020. 10. 4. 10:13
반응형

배열 대 목록: 언제 사용합니까?


MyClass[] array;
List<MyClass> list;

하나가 다른 것보다 선호되는 시나리오는 무엇입니까? 그리고 왜?


실제로 어레이를 사용하려는 경우는 드뭅니다. List<T>배열의 크기를 조정하는 것은 비용이 많이 들기 때문에 데이터를 추가 / 제거하고 싶을 때 언제든지를 사용 하십시오. 데이터가 고정 길이라는 것을 알고 있고 매우 특정한 이유 (벤치마킹 후)에 대해 미세 최적화하려는 경우 어레이가 유용 할 수 있습니다.

List<T>LINQ는 배열보다 훨씬 더 많은 기능을 제공하며 거의 항상 올바른 선택입니다. params물론 논쟁을 제외하고 . ;-피

카운터로서 List<T>-1 차원입니다. int[,]또는 같은 직사각형 (기타) 배열이 string[,,]있지만 객체 모델에서 이러한 데이터를 모델링하는 다른 방법이 있습니다 (필요한 경우).

또한보십시오:

즉, protobuf-net 프로젝트 에서 배열을 많이 사용합니다 . 전적으로 성능 :

  • 많은 비트 시프 팅을 수행하므로 a byte[]는 인코딩에 매우 중요합니다.
  • byte[]기본 스트림 (및 vv)으로 보내기 전에 채우는 로컬 롤링 버퍼를 사용합니다 . BufferedStream보다 빠르다 .
  • 크기가 빌드되면 고정되고 매우 빨라야하기 때문에 내부적으로 객체의 배열 기반 모델 ( Foo[]보다는 List<Foo>)을 사용합니다.

그러나 이것은 확실히 예외입니다. 일반적인 LOB (기간 업무) 처리의 경우 List<T>항상 이깁니다.


내가 놀란 링크를 추가하는 것에 대한 대답은 아직 언급되지 않았습니다 . "다소 유해한 것으로 간주되는 배열" 에 대한 Eric의 Lippert 블로그 항목 .

제목에서 실용적인 곳에서는 컬렉션 사용을 제안한다고 판단 할 수 있습니다. 그러나 Marc가 올바르게 지적했듯이 배열이 실제로 유일한 실용적인 솔루션 인 곳이 많습니다.


권장하는 다른 답변에도 불구하고 다음을 List<T>처리 할 때 배열을 사용하고 싶을 것입니다.

  • 이미지 비트 맵 데이터
  • 기타 저수준 데이터 구조 (예 : 네트워크 프로토콜)

당신이 정말로 성능에 관심이 없다면 "왜 C ++ 대신 .Net을 사용하고 있는가?" List <>를 고수해야합니다. 유지 관리가 더 쉽고 배후에서 배열 크기를 조정하는 모든 더러운 작업을 수행합니다. (필요한 경우 List <>는 배열 크기를 선택하는 데 매우 현명하므로 일반적으로 필요하지 않습니다.)


컬렉션 자체의 불변성이 클라이언트와 공급자 코드 간의 계약의 일부인 경우 (컬렉션 내 항목의 불변성 일 필요는 없음) 및 IEnumerable이 적합하지 않은 경우 List보다 배열 을 우선적으로 사용해야 합니다.

예를 들면

var str = "This is a string";
var strChars = str.ToCharArray();  // returns array

"strChars"를 수정해도 "str"의 기본 유형에 대한 구현 수준 지식과 관계없이 원래 "str"개체가 ​​변경되지는 않습니다.

하지만

var str = "This is a string";
var strChars = str.ToCharList();  // returns List<char>
strChars.Insert(0, 'X');

이 경우 삽입 메서드가 원래 "str"개체를 변경하는지 여부는 해당 코드 조각만으로는 명확하지 않습니다. 이러한 결정을 내리려면 String에 대한 구현 수준의 지식이 필요하며, 이는 Design by Contract 접근 방식을 깨뜨립니다. String의 경우 큰 문제는 아니지만 거의 모든 다른 경우에 큰 문제가 될 수 있습니다. List를 읽기 전용으로 설정하면 도움이되지만 컴파일 타임이 아닌 런타임 오류가 발생합니다.


내가 필요 해요 정확히 얼마나 많은 요소를 알고있는 경우에, 나는 5 개 요소 만 필요하다고 이제까지 나는 배열을 사용하여 5 요소. 그렇지 않으면 List <T>를 사용합니다.


대부분의 경우 a를 사용하는 List것으로 충분합니다. A List는 내부 어레이를 사용하여 데이터를 처리하고 List현재 용량보다 더 많은 요소를 추가 할 때 어레이의 크기를 자동으로 조정 하므로 용량을 미리 알아야하는 어레이보다 사용하기가 더 쉽습니다.

C #의 목록에 대한 자세한 내용은 http://msdn.microsoft.com/en-us/library/ms379570(v=vs.80).aspx#datastructures20_1_topic5참조 하거나 디 컴파일 System.Collections.Generic.List<T>합니다.

다차원 데이터가 필요한 경우 (예 : 행렬 사용 또는 그래픽 프로그래밍에서) 아마도 array대신 사용할 것입니다.

항상 그렇듯이 메모리 나 성능이 문제라면이를 측정하십시오! 그렇지 않으면 코드에 대해 잘못된 가정을 할 수 있습니다.


Another situation not yet mentioned is when one will have a large number of items, each of which consists of a fixed bunch of related-but-independent variables stuck together (e.g. the coordinates of a point, or the vertices of a 3d triangle). An array of exposed-field structures will allow the its elements to be efficiently modified "in place"--something which is not possible with any other collection type. Because an array of structures holds its elements consecutively in RAM, sequential accesses to array elements can be very fast. In situations where code will need to make many sequential passes through an array, an array of structures may outperform an array or other collection of class object references by a factor of 2:1; further, the ability to update elements in place may allow an array of structures to outperform any other kind of collection of structures.

Although arrays are not resizable, it is not difficult to have code store an array reference along with the number of elements that are in use, and replace the array with a larger one as required. Alternatively, one could easily write code for a type which behaved much like a List<T> but exposed its backing store, thus allowing one to say either MyPoints.Add(nextPoint); or MyPoints.Items[23].X += 5;. Note that the latter would not necessarily throw an exception if code tried to access beyond the end of the list, but usage would otherwise be conceptually quite similar to List<T>.


Lists in .NET are wrappers over arrays, and use an array internally. The time complexity of operations on lists is the same as would be with arrays, however there is a little more overhead with all the added functionality / ease of use of lists (such as automatic resizing and the methods that come with the list class). Pretty much, I would recommend using lists in all cases unless there is a compelling reason not to do so, such as if you need to write extremely optimized code, or are working with other code that is built around arrays.


Since no one mention: In C#, an array is a list. MyClass[] and List<MyClass> both implement IList<MyClass>. (e.g. void Foo(IList<int> foo) can be called like Foo(new[] { 1, 2, 3 }) or Foo(new List<int> { 1, 2, 3 }) )

So, if you are writing a method that accepts a List<MyClass> as an argument, but uses only subset of features, you may want to declare as IList<MyClass> instead for callers' convenience.

Details:


It completely depends on the contexts in which the data structure is needed. For example, if you are creating items to be used by other functions or services using List is the perfect way to accomplish it.

Now if you have a list of items and you just want to display them, say on a web page array is the container you need to use.


Rather than going through a comparison of the features of each data type, I think the most pragmatic answer is "the differences probably aren't that important for what you need to accomplish, especially since they both implement IEnumerable, so follow popular convention and use a List until you have a reason not to, at which point you probably will have your reason for using an array over a List."

Most of the time in managed code you're going to want to favor collections being as easy to work with as possible over worrying about micro-optimizations.


They may be unpopular, but I am a fan of Arrays in game projects. - Iteration speed can be important in some cases, foreach on an Array has significantly less overhead if you are not doing much per element - Adding and removing is not that hard with helper functions - Its slower, but in cases where you only build it once it may not matter - In most cases, less extra memory is wasted (only really significant with Arrays of structs) - Slightly less garbage and pointers and pointer chasing

That being said, I use List far more often than Arrays in practice, but they each have their place.

It would be nice if List where a built in type so that they could optimize out the wrapper and enumeration overhead.


Populating a list is easier than an array. For arrays, you need to know the exact length of data, but for lists, data size can be any. And, you can convert a list into an array.

List<URLDTO> urls = new List<URLDTO>();

urls.Add(new URLDTO() {
    key = "wiki",
    url = "https://...",
});

urls.Add(new URLDTO()
{
    key = "url",
    url = "http://...",
});

urls.Add(new URLDTO()
{
    key = "dir",
    url = "https://...",
});

// convert a list into an array: URLDTO[]
return urls.ToArray();

Arrays Vs. Lists is a classic maintainability vs. performance problem. The rule of thumb that nearly all developers follow is that you should shoot for both, but when they come in to conflict, choose maintainability over performance. The exception to that rule is when performance has already proven to be an issue. If you carry this principle in to Arrays Vs. Lists, then what you get is this:

Use strongly typed lists until you hit performance problems. If you hit a performance problem, make a decision as to whether dropping out to arrays will benefit your solution with performance more than it will be a detriment to your solution in terms of maintenance.

참고URL : https://stackoverflow.com/questions/434761/array-versus-listt-when-to-use-which

반응형