[Mono-devel-list] Performance w/ boxing

Joshua Tauberer tauberer at for.net
Fri Feb 20 10:28:58 EST 2004


Jonathan Gilbert wrote:
> Of course, you can always do it Java-style and create a class to wrap an
> integer. You can use operator overloading to make it transparent, too.

If the caller doesn't need to pass specifically null but some other 
invalid-value-signaling value, a struct should, I think, get better 
performance:

public struct Integer
{
   public static Integer NULL = new Integer();
	
   private readonly bool NotNull; // so that default initialization to 
false means it's null
   public readonly int Value;

   public Integer(int value) { NotNull = true; Value = value; }

   public bool IsNull { get { return !NotNull; } }

   public static implicit operator int(Integer obj) { return obj.Value; }
   public static implicit operator Integer(int val) { return new
Integer(val); }
}

void function(Integer notboxed) {
   if (notboxed.IsNull) { System.Console.WriteLine("null"); }
   else { System.Console.WriteLine(notboxed * 5); }
}

public static void Main() {
   function(Integer.NULL);
   function(7);
}

Unfortunately, I don't think there's a way to implicitly cast from a 
null to anything else.

-- 
- Joshua Tauberer

http://taubz.for.net

** Nothing Unreal Exists **





More information about the Mono-devel-list mailing list