快速連結

2017年8月9日

【筆記】List用ToArray轉成Array的理由

最近為了煩惱要不要把List轉成Array傳給function去做處理,爬了一些文,很多年前就有回答:C# List.ToArray performance is bad?


底下有個回答寫的很清楚:
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.
轉換驗證:
C# Convert List to Array - Dot Net Perls

列出來XD