Alex Rivera | Logout

Does an empty array in .NET use any space?

Asked 2008-09-30T06:07:53.807
26

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

Here's a simplified example:

string[] GetTheStuff() {
    List<string> s = null;
    if( somePredicate() ) {
        s = new List<string>(); // imagine we load some data or something
    }
    return (s == null) ? 
        new string[0] :
        s.ToArray();
}

The question is, how expensive is the new string[0] ?
Should I just return null and make the caller accept null as a valid way of indicating "nothing was found"?

NB: This is being called in a loop which gets run hundreds and hundreds of times, so it's one of the few cases where I think this kind of optimiziation is not actually 'premature'.

PS: And even if it was premature, I'd still like to know how it works :-)

Update:

Initially when I asked if it used any space, I was thinking of things from the 'C/C++' point of view, kind of like how in C, writing char a[5]; will allocate 5 bytes of space on the stack, and char b[0]; will allocate 0 bytes.

I realise this is not a good fit for the .NET world, but I was curious if this was something that the compiler or CLR would detect and optimize out, as a non-resizeable array of size zero really shouldn't (as far as I can see?) require any storage space.

Edit
Report

2 Answers

2

This is not a direct answer to your question.

Read why arrays are considered somewhat harmful. I would suggest you to return an IList<string> in this case and restructure the code a little bit:

IList<string> GetTheStuff() {
    List<string> s = new List<string>();
    if( somePredicate() ) {
        // imagine we load some data or something
    }
    return s;
}

In this way the caller doesn't have to care about empty return values.


EDIT: If the returned list should not be editable you can wrap the List inside a ReadOnlyCollection. Simply change the last line to. I also would consider this best practice.

    return new ReadOnlyCollection(s);
answered 2008-09-30T06:18:32.423
0

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;
}
answered 2008-09-30T06:15:43.663

Your Answer