开发者

Return by value or reference?

If we have two methods, one returning a variable by value, and the other by reference, which has the highest performance?

myObj.Method1(out var);

or

var = myObj.Method2();

I guess the first version is more efficient but, does that mean you should always build methods that return values by reference? Or is 开发者_如何学JAVAthere any reason to return variables by value?

Thanks.


The performance difference will be immeasurably small or nonexistent.

You are incorrectly assuming that the two versions have different semantics.
For reference types, both methods will copy a reference exactly once.

For large value types, out parameters can be faster, since you don't need a separate temporary local.
Always measure before jumping to conclusions!

Do not use out parameters unless you need to return 2 values.


There is absolutely no performance difference as long as they are reference type.

By the way, if you define your method so that it returns a value, this will not be by value. Return type is always is by reference unless the type is a value type.


There will be little to no difference for reference types (classes), because in both cases it the value is returned by reference.

For value types (structs) there might be a difference if the type contains many fields, in that case returning using the out parameter is a bit faster.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜