[Mono-devel-list] Zero Length Arrays

Paolo Molaro lupus at ximian.com
Mon Jan 12 10:12:09 EST 2004

On 01/12/04 Jeroen Frijters wrote:
> Ben Maurer wrote:
> > So, today, I realized that there is a VERY simple solution. In

It's not simple at all, regardless of the use of uppercase characters:-)
It's also not much of an optimization, since:
*) it adds yet another cond branch to the fast path (0-length arrays are
a small special case): so it slows down the common code
*) since you need to deal with per domain and per type caches, you need
memory and hashtable lookups and at the end of they day that's not much
faster than a call to GC_malloc.

> > mono_array_new, if it finds that it will be creating a zero length
> > array, it should used a cached zero length array.
> ECMA says:
> "The newarr instruction pushes a reference to a *new* zero-based,
> one-dimensional array" (my emphasis).
> This optimization is not allowed. Plain and simple.

Absolutely. The runtime can't do that kind of stuff at the newarr level.

> Piers Haken wrote:
> > What about locking?
> This is why the optimization isn't legal. The following pattern is
> should work:
> object myLock = new object[0];
> lock(myLock)
> {
> }

The optimization can be applied to the internal implementation of the
assemblies (though in that case a null could be just as good), since
we can audit the code not to do the silly lock, but, of course, this
needs to be done completely in C# code, there is no valid reason for
doing it inside the runtime.
There is also a grey area for arrays returned by, for example, the 
Reflection code: the documentation doesn't state that the returned
arrays should be unique even when they are zero-length. This pattern is
already used for some things:

	string s = String.Concat (null);
	Console.WriteLine (Object.ReferenceEquals (s, String.Empty));

will print True both on Mono and MS.


lupus at debian.org                                     debian/rules
lupus at ximian.com                             Monkeys do it better

More information about the Mono-devel-list mailing list