Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET return value optimization

Tags:

c#

Will the .NET compiler optimize this:

public MyObject GetNewObject()
{
    var newCurrentObject = myObjectFactory.CreateNew(
                                 DateTime.Now, 
                                 "Frank", 
                                 41, 
                                 secretPassword);

    return newCurrentObject;
}

to execute with the same number of instructions/memory as this:

public MyObject GetNewObject()
{
    return myObjectFactory.CreateNew(
                        DateTime.Now, 
                        "Frank", 
                        41, 
                        secretPassword);
}

Or will the local variable result in extra time and memory being spent to create a reference (newObject) to the MyObject only destroy it the next line once it's out of scope.

I ask because, performance all the same, I find the first to be more readable as a local variable name can often give the next developer some context as to what we're doing here.

like image 688
Piers MacDonald Avatar asked Apr 21 '15 19:04

Piers MacDonald


People also ask

How does return value optimization work?

In the context of the C++ programming language, return value optimization (RVO) is a compiler optimization that involves eliminating the temporary object created to hold a function's return value. RVO is allowed to change the observable behaviour of the resulting program by the C++ standard.

What is named return value optimization?

(Named) Return value optimization is a common form of copy elision. It refers to the situation where an object returned by value from a method has its copy elided. The example set forth in the standard illustrates named return value optimization, since the object is named.

Does C have return value optimization?

> Note also that C doesn't have return-value-optimization, hence all your struct-returning functions will cause a call to memcpy (won't happen when compiled in C++ mode of course).

What is NRVO?

the NRVO (Named Return Value Optimization)


1 Answers

Assuming MyObject is a reference type the same x86 will be generated for both cases. The JIT is quite competent at optimizing away scalar temporaries and assignments. This is one of the most basic optimizations there is. Pretty much any optimizer uses SSA form internally and this optimization almost falls out of SSA form.

Assuming MyObject is a struct: I have extensively tested the .NET 4.5 JIT and the new RyuJIT for struct optimizations. The .NET JITs generally do not optimize structs assignments and (local) variables. Code is literally translated except for one minor case that does not apply here. Expect totally literal machine code. Even if you say a = a; or a.x = 1; a.x = 1; you get exactly that as machine code. Send a mail to the team if structs are important to you. Now is still time to make the changes.

like image 145
usr Avatar answered Sep 29 '22 17:09

usr