Does an empty array in .NET use any space?

后端 未结 9 1512
暗喜
暗喜 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:36

    Even if it's being called "hundreds and hundreds" of times, I'd say it's a premature optimization. If the result is clearer as an empty array, use that.

    Now for the actual answer: yes, an empty array takes some memory. It has the normal object overhead (8 bytes on x86, I believe) and 4 bytes for the count. I don't know whether there's anything beyond that, but it's not entirely free. (It is incredibly cheap though...)

    Fortunately, there's an optimization you can make without compromising the API itself: have a "constant" of an empty array. I've made another small change to make the code clearer, if you'll permit...

    private static readonly string[] EmptyStringArray = new string[0];
    
    string[] GetTheStuff() {
        if( somePredicate() ) {
            List s = new List(); 
            // imagine we load some data or something
            return s.ToArray();
        } else {
            return EmptyStringArray;
        }
    }
    

    If you find yourself needing this frequently, you could even create a generic class with a static member to return an empty array of the right type. The way .NET generics work makes this trivial:

    public static class Arrays {
        public static readonly Empty = new T[0];
    }
    

    (You could wrap it in a property, of course.)

    Then just use: Arrays.Empty;

    EDIT: I've just remembered Eric Lippert's post on arrays. Are you sure that an array is the most appropriate type to return?

提交回复
热议问题