I have some code where I\'m returning an array of objects.
Here\'s a simplified example:
string[] GetTheStuff() {
List s = null;
I would guess that an empty array uses only the space needed to allocate the object pointer itself.
From memory the API guidelines say that you should always return an empty array from a method that returns an array rather than returning null, so I'd leave your code the way it is regardless. That way the caller knows he's guaranteed to get an array (even an empty one) and need not check for null with each call.
Edit: A link about returning empty arrays:
http://wesnerm.blogs.com/net_undocumented/2004/02/empty_arrays.html
If I understand correctly, a small amount of memory will be allocated for the string arrays. You code essentially requires a generic list to be created anyway, so why not just return that?
[EDIT]Removed the version of the code that returned a null value. The other answers advising against null return values in this circumstance appear to be the better advice[/EDIT]
List<string> GetTheStuff()
{
List<string> s = new List<string();
if (somePredicarte())
{
// more code
}
return s;
}
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<string> s = new List<string>();
// 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<T> {
public static readonly Empty = new T[0];
}
(You could wrap it in a property, of course.)
Then just use: Arrays<string>.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?