简体   繁体   中英

Will there be a performance gain by having parameters of methods as reference type?

I have a public method which calls several other private methods, repeatedly. These private methods accept one or more parameters (most of them are strings) and have a return type. All of these parameters are value type parameters.

I would like to know if I can improve the performance of my ASP.NET application my converting all these value type parameters to reference type, since the memory consumption of reference type would be much less than that of value type.

Thanks in advance.

Unless your value types are huge, this is probably a unnecessary micro-optimization. And if they are, you may want to reconsider your design.

As always, benchmark first to see where the real bottlenecks are.

Code:

while (true)
{
  Stopwatch watch = new Stopwatch();
  watch.Start();
  Int64 myNum = 123456789;
  for (int i = 0; i < 10000000; i++)
  {
    myNum++;
    DoSomething(myNum);
  }
  watch.Stop();
  Console.WriteLine("Time: " + watch.ElapsedMilliseconds + "ms");
}

private void DoSomething(Int64 bigNum)
{
  Int64 fake = bigNum - 1;
}

Without ref:

Time: 237ms
Time: 245ms
Time: 252ms
Time: 237ms
Time: 235ms

With ref:

Time: 242ms
Time: 238ms
Time: 232ms
Time: 248ms
Time: 232ms
Time: 233ms
Time: 232ms

Very basic test, but it doesn't appear to make a difference in the most basic case.

No, in normal circumstances it would only add overhead to pass parameters by reference.

If you have performance problems because your value types are large, the root of the problem is the design pf the value types, and there is where you should tackle the problem.

A value type should not be larger than 16 bytes, according to the recommendations from Microsoft. If they are larger, they will not perform well. Small value types can be copied with one or two CPU instructions, while larger value types are copied using a loop.

IF you use classes instead, they will be passed as references by default.

I guess yes. But you wont see the difference unless you call those methods few milion times. This actualy works only for bigger structures. Integers and such should be unafected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM