Does an empty array in .NET use any space?

后端 未结 9 1537
暗喜
暗喜 2021-01-01 10:39

I have some code where I\'m returning an array of objects.

Here\'s a simplified example:

string[] GetTheStuff() {
    List s = null;
             


        
9条回答
  •  我在风中等你
    2021-01-01 11:15

    Yes, as others have said, the empty array takes up a few bytes for the object header and the length field.

    But if you're worried about performance you're focusing on the wrong branch of execution in this method. I'd be much more concerned about the ToArray call on the populated list which will result in a memory allocation equal to its internal size and a memory copy of the contents of the list into it.

    If you really want to improve performance then (if possible) return the list directly by making the return type one of: List, IList, ICollection, IEnumerable depending on what facilities you need from it (note that less specific is better in the general case).

提交回复
热议问题