是否传递一个&QUOT值类型;从"参数引起的变量进行装箱? [英] Does passing a value type in an "out" parameter cause the variable to be boxed?

查看:136
本文介绍了是否传递一个&QUOT值类型;从"参数引起的变量进行装箱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,装箱和拆箱都是比较昂贵的性能方面。我想知道的是:



是否传递一个值类型的方法的退出参数事业装箱/的拆箱变量(从而影响性能)?可以在编译器优化送人

  INT多少?; 
布尔结果= Int32.TryParse(值,数出);


解决方案

正如其他人所指出的,这里没有拳击。当你传递一个变量对应于out或ref参数一个参数,你在做什么是的做的别名变量的。你没有做任何事情到的的变量。你让两个变量代表相同的存储位置。



拳击只发生在一个值类型的值转换为引用类型的值,而且也没有任何在你的榜样的转换。当然,引用类型必须是System.Object的,System.ValueType,System.Enum或任何接口。通常它是相当清楚的;有一个在代码中显式或隐式转换。但是,可以在某些地方是不太清楚。例如,当一个结构的基本类型的一个不重写虚方法被调用时,有拳击。 (也有在某些种类的泛型类型的限制可能会导致意外拳离奇的情况,但他们通常不会拿出练习。)


I'm aware that boxing and unboxing are relatively expensive in terms of performance. What I'm wondering is:

Does passing a value type to a method's out parameter cause boxing/unboxing of the variable (and thus a performance hit)? Can the compiler optimize this away?

  int number;
  bool result = Int32.TryParse(value, out number);

解决方案

As others have pointed out, there's no boxing here. When you pass a variable as an argument corresponding to an out or ref parameter, what you are doing is making an alias to the variable. You are not doing anything to the value of the variable. You're making two variables represent the same storage location.

Boxing only happens when a value of a value type is converted to a value of a reference type, and there's no conversion of any kind in your example. The reference type must of course be System.Object, System.ValueType, System.Enum or any interface. Usually it is pretty clear; there's an explicit or implicit conversion in the code. However, there can be circumstances where it is less clear. For example, when a not-overridden virtual method of a struct's base type is called, there's boxing. (There are also bizarre situations in which certain kinds of generic type constraints can cause unexpected boxing, but they don't usually come up in practice.)

这篇关于是否传递一个&QUOT值类型;从"参数引起的变量进行装箱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆