C#.NET中按值传递与按引用传递的性能 [英] Performance of pass by value vs. pass by reference in C# .NET

查看:156
本文介绍了C#.NET中按值传递与按引用传递的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个轻量级的类,该类的构造函数带有大约10个参数。该类不更改参数值。它只是通过构造函数在本地存储值。

I've created a lightweight class with a constructor that takes around 10 parameters. The class does not change the parameter values; it just stores the values locally via the constructor.

某些参数是引用类型(字符串,类),其他参数是值类型(int,bool,枚举)。

Some parameters are reference types (strings, classes) and others are value types (int, bool, enums).

我的问题是我应该通过引用传递所有参数(类除外),即使用关键字 ref

My question is should I pass all parameters (except the classes) via reference, i.e., using the keyword ref?

我在这里考虑的是性能。

My consideration here is performance.

推荐答案

仅使用 ref 如果该方法需要更改参数,并且这些更改需要传递给调用代码。仅当通过分析器运行它并确定瓶颈确实是将方法参数复制到堆栈的CLR时,才应对此进行优化。

Only use ref if the method needs to alter the parameters, and these changes need to be passed onto the calling code. You should only optimize this if you have run it through a profiler and determined that the bottleneck is indeed the CLR copying the method parameters onto the stack.

请记住CLR已针对使用参数的调用方法进行了优化,因此我不认为这会成为问题。

Bear in mind the CLR is heavily optimized for calling methods with parameters, so I shouldn't think this would be the issue.

这篇关于C#.NET中按值传递与按引用传递的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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