[Mono-devel-list] Zero Length Arrays
bmaurer at users.sourceforge.net
Sun Jan 11 12:43:47 EST 2004
In my optimization work, I have found one interesting problem. According
the C# design guidelines:
> String and Array properties should never return a null reference. Null
> can be difficult to understand in this context.... The general rule is
> that null, empty string (""), and empty (0 item) arrays should be
> treated the same way. Return an empty array instead of a null
However, this leads to a problem. In code such as:
// Build up the list
object  ret = new object [listBuilder.Count];
You often end up creating arrays of zero length. This cases extra memory
allocation. So, in many performance critical places, we do:
static object  noObjects = new object ;
if (listBuilder.Count == 0) return noObjects;
However, this pattern is very messy. It requires alot more thinking on
the part of the programmer. It also will not work for something, like
So, I talked with Miguel about this problem. My first idea what that MCS
could optimize this. In other words, if you did:
new object ;
That it would create a static field for you that held the object.
However, this really didnt fix the problem. You still had to think about
it, and add an if statement.
So, today, I realized that there is a VERY simple solution. In
mono_array_new, if it finds that it will be creating a zero length
array, it should used a cached zero length array.
For this to be a win, I think we must do it so that we need not lock in
that method. I would love comments from the runtime gurus.
More information about the Mono-devel-list