Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

c# - Does passing a value type in an "out" parameter cause the variable to be boxed?

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...