C# List.ToArray performance is bad?

后端 未结 7 827
礼貌的吻别
礼貌的吻别 2020-12-14 01:22

I\'m using .Net 3.5 (C#) and I\'ve heard the performance of C# List.ToArray is \"bad\", since it memory copies for all elements to form a new array. Is

7条回答
  •  孤街浪徒
    2020-12-14 01:39

    Yes, it's true that it does a memory copy of all elements. Is it a performance problem? That depends on your performance requirements.

    A List contains an array internally to hold all the elements. The array grows if the capacity is no longer sufficient for the list. Any time that happens, the list will copy all elements into a new array. That happens all the time, and for most people that is no performance problem.

    E.g. a list with a default constructor starts at capacity 16, and when you .Add() the 17th element, it creates a new array of size 32, copies the 16 old values and adds the 17th.

    The size difference is also the reason why ToArray() returns a new array instance instead of passing the private reference.

提交回复
热议问题