Alex Rivera | Logout

Variable number of arguments without boxing the value-types?

Asked 2009-12-11T21:28:18.847
11
public void DoSomething(params object[] args)
{
    // ...
}

The problem with the above signature is that every value-type that will be passed to that method will be boxed implicitly, and this is serious performance issue for me.

Is there a way to declear a method that accepts variable number of arguments without boxing the value-types?

Thanks.

Edit
Report

2 Answers

3

Not presently, no, and I haven't seen anything addressing the issue in the .NET 4 info that's been released.

If it's a huge performance problem for you, you might consider several overloads of commonly seen parameter lists.

I wonder, though: is it really a performance problem, or are you prematurely optimizing?

answered 2009-12-11T21:33:08.237
3

Let's assume the code you're calling this method from is aware of argument types. If so, you can pack them into appropriate Tuple type from .NET 4, and pass its instance (Tuple is reference type) to such method as object (since there is no common base for all the Tuples).

The main problem here is that it isn't easy to process the arguments inside this method without boxing / unboxing, and likely, even without reflection. Try to think what must be done to extract, let's say, Nth argument without boxing. You'll end up with understanding you must either deal with dictionary lookup(s) there (involving either regular Dictionary<K,V> or internal dictionaries used by CLR), or with boxing. Obviously, dictionary lookups are much more costly.

I'm writing this because actually we developed a solution for very similar problem: we must be able to operate with our own Tuples without boxing - mainly, to compare and deserialize them (Tuples are used by database engine we develop, so performance of any basic operation is really essential in our case).

But:

  • We end up with pretty complex solution. Take a look e.g. at TupleComparer.
  • Effect of absence of boxing is actually not as good as we expected: each boxing / unboxing operation is replaced by a single array indexing and few virtual method calls, the cost of both ways is almost identical.

The only benefit of approach we developed is that we don't "flood" Gen0 by

answered 2009-12-11T22:13:41.453

Your Answer