C# List.ToArray performance is bad?

后端 未结 7 824
礼貌的吻别
礼貌的吻别 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:46

    Reasons to call ToArray()

    • If the returned value is not meant to be modified, returning it as an array makes that fact a bit clearer.
    • If the caller is expected to perform many non-sequential accesses to the data, there can be a performance benefit to an array over a List<>.
    • If you know you will need to pass the returned value to a third-party function that expects an array.
    • Compatibility with calling functions that need to work with .NET version 1 or 1.1. These versions don't have the List<> type (or any generic types, for that matter).

    Reasons not to call ToArray()

    • If the caller ever does need to add or remove elements, a List<> is absolutely required.
    • The performance benefits are not necessarily guaranteed, especially if the caller is accessing the data in a sequential fashion. There is also the additional step of converting from List<> to array, which takes processing time.
    • The caller can always convert the list to an array themselves.

    taken from here

提交回复
热议问题