c# - Does an empty array in .NET use any space? -


i have code i'm returning array of objects.

here's simplified example:

string[] getthestuff() {     list<string> s = null;     if( somepredicate() ) {         s = new list<string>(); // imagine load data or     }     return (s == null) ?          new string[0] :         s.toarray(); } 

the question is, how expensive new string[0] ?
should return null , make caller accept null valid way of indicating "nothing found"?

nb: being called in loop gets run hundreds , hundreds of times, it's 1 of few cases think kind of optimiziation not 'premature'.

ps: , if premature, i'd still know how works :-)

update:

initially when asked if used space, thinking of things 'c/c++' point of view, kind of how in c, writing char a[5]; allocate 5 bytes of space on stack, , char b[0]; allocate 0 bytes.

i realise not fit .net world, curious if compiler or clr detect , optimize out, non-resizeable array of size 0 shouldn't (as far can see?) require storage space.

even if it's being called "hundreds , hundreds" of times, i'd it's premature optimization. if result clearer empty array, use that.

now actual answer: yes, empty array takes memory. has normal object overhead (8 bytes on x86, believe) , 4 bytes count. don't know whether there's beyond that, it's not entirely free. (it is incredibly cheap though...)

fortunately, there's optimization can make without compromising api itself: have "constant" of empty array. i've made small change make 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 load data or         return s.toarray();     } else {         return emptystringarray;     } } 

if find needing frequently, create generic class static member return empty array of right type. way .net generics work makes trivial:

public static class arrays<t> {     public static readonly empty = new t[0]; } 

(you wrap in property, of course.)

then use: arrays<string>.empty;

edit: i've remembered eric lippert's post on arrays. sure array appropriate type return?


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -