C#元组,构造-解构性能 [英] C# tuples, construction-deconstruction performance

查看:97
本文介绍了C#元组,构造-解构性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在写一些以下风格的代码:

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);

现在,我想知道这种编写代码的方式对性能的影响.我想在这里元组的构造-解构可以被编译器优化掉.但也许不是?请注意, b1, b2, ..., bn 可以是值或表达式.而且,如果无法进行优化,n 的大小也很重要(我认为).

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?

提前致谢.

推荐答案

像这样使用,它们甚至不是真正的 ValueTuple 因为编译器已经把这一切都去掉了.

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

比较和对比 IL:

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

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

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

前往:

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

一样.

所以...一旦编译器发挥了它的魔力,它实际上只是一种风格选择.

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

这篇关于C#元组,构造-解构性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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