C# tuples, construction-deconstruction performance

2019-08-18 16:21发布

问题:

I have been writing some code in the style of:

a1 = b1;
a2 = b2;
a3 = b3;
...
an = bn;

Suddenly I realize that for me, and for the context that I am writing the current algorithm (...) is more aesthetically pleasing to write some of these assignments in the form of:

(a1, a2, a3, ..., an) = (b1, b2, b3, ..., bn);

Now, I would like to know about the impact that this way of writing code can have on the performance. I suppose that here the construction-deconstruction of tuples can be optimized away by the compiler. But maybe not? Note that b1, b2, ..., bn can be values or expressions. And also if the optimization cannot be done, the size of n will matter (I think).

So, to have a concrete question: Can someone explain the difference in performance about the 2 ways of writing code, taking into account all the possible details?

Thanks in advance.

回答1:

Used like this, they aren't even really ValueTuple at all because the compiler has stripped this all away.

Compare and contrast the IL:

var a = 1;
var b = 2;
var c = 3;
var d = 4;

goes to

IL_0001:  ldc.i4.1    
IL_0002:  stloc.0     // a
IL_0003:  ldc.i4.2    
IL_0004:  stloc.1     // b
IL_0005:  ldc.i4.3    
IL_0006:  stloc.2     // c
IL_0007:  ldc.i4.4    
IL_0008:  stloc.3     // d

and

var (a, b, c, d) = (1, 2, 3, 4);

goes to:

IL_0001:  ldc.i4.1    
IL_0002:  stloc.0     // a
IL_0003:  ldc.i4.2    
IL_0004:  stloc.1     // b
IL_0005:  ldc.i4.3    
IL_0006:  stloc.2     // c
IL_0007:  ldc.i4.4    
IL_0008:  stloc.3     // d

The same.

So... once the compiler has done its magic, it's really just a style choice.