开发者

What performance improvements have been made to the boxing and unboxing operations in the CLR, if any?

开发者 https://www.devze.com 2023-04-13 02:00 出处:网络
I attended a seminar a few months ago and the speaker made the statement that the general cost of a boxing or unboxing operation has been reduced since .NET 1.1.I\'ve looked through my (poor) notes an

I attended a seminar a few months ago and the speaker made the statement that the general cost of a boxing or unboxing operation has been reduced since .NET 1.1. I've looked through my (poor) notes and can't determine if this statement makes reference to the box and unbox instructions, or to the introduction of 开发者_如何学JAVAclasses (i.e. generic types) that make boxing/unboxing less likely to occur.

Has there been a performance improvement in the CLR boxing-related instructions between .NET 1.1 and .NET 4.0, and if so, where can I find information on the measurements that show the gains?


I can't comment on the performance (for that you'd need profiling, etc) - but one interesting change here is the constrained op-code, that is used in particular with generics. The advantage here is that for a method like:

static void DoSomething<T>(T x, T y) where T : IComparable<T>
{
    if(x.CompareTo(y) < 0) { /* whatever */ }
}

it will use a constrained-call for CompareTo, which allows it to either use a static-call to the method implementation on a value-type (without an unbox), or use a virtual-call if it is a reference-type. Normally, calling an interface-based method on a value-type requires a box, so this is pretty helpful.


Boxing and unboxing should be avoided as much as possible. From MSDN:

It is best to avoid using value types in situations where they must be boxed a high number of times, for example in non-generic collections classes such as System.Collections::ArrayList. You can avoid boxing of value types by using generic collections such as System.Collections.Generic::List. Boxing and unboxing are computationally expensive processes. When a value type is boxed, an entirely new object must be created. This can take up to 20 times longer than a simple reference assignment. When unboxing, the casting process can take four times as long as an assignment.

MS have done what they can to minimize the cost of boxing operations themselves, but there's only so much that can be done.

MUCH better performance improvement can be achieved by eliminating as much boxing as possible from one's code. Avoiding non-generic containers is a VERY effective way of massively reducing boxing. Being able to use generic containers is one of the primary benefits of moving from NETFX 1.1 to 2.0+.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号