三元运算符?:vs if ... else ..哪一个更快? [英] Ternary operator ?: vs if…else ..which one is more faster ?

查看:144
本文介绍了三元运算符?:vs if ... else ..哪一个更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hii,





哪个更快,三元还是其他,



以及哪一个有利于维护

Hii ,


Which is is more faster , ternary or if else ,

and which one is good for maintain

ability of the code.

推荐答案

拿这个代码:

Taking this code:
bool rv;
string check = "";

if ( check == "not" )
{
    rv = false;
}
else
{
    rv = true;
}

rv = ( check == "not" ) ? false : true;



这将产生这个IL:


That will produce this IL:

.method family hidebysig 
	instance void Page_Load (
		object sender,
		class [mscorlib]System.EventArgs e
	) cil managed 
{
	// Method begins at RVA 0x2050
	// Code size 55 (0x37)
	.maxstack 2
	.locals init (
		[0] bool rv,
		[1] string check,
		[2] bool CS


4


0000


IL_0000:nop
IL_0001:ldstr
IL_0006:stloc.1
IL_0007:ldloc.1
IL_0008: ldstrnot
IL_000d:call bool [mscorlib] System.String :: op_Equality(string,string)
IL_0012:ldc.i4.0
IL_0013:ceq
IL_0015: stloc.2
IL_0016:ldloc.2
IL_0017:brtrue.s IL_001f

IL_0019:nop
IL_001a:ldc.i4.0
IL_001b: stloc.0
IL_001c:nop
IL_001d:br.s IL_0023

IL_001f:nop
IL_0020:ldc.i4.1
IL_0021:stloc.0
IL_0022:nop

IL_0023:ldloc.1
IL_0024:ldstrnot
IL_0029:call bool [mscorlib] System.String :: op_Equality(string,string)
IL_002e:brtrue.s IL_0033

IL_0030:ldc.i4.1
IL_0031:br.s IL_0034

IL_0033:ldc.i4.0

IL_0034:nop
IL_0035:stloc.0
IL_0036:ret
} //方法结束
0000 ) IL_0000: nop IL_0001: ldstr "" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: ldstr "not" IL_000d: call bool [mscorlib]System.String::op_Equality(string, string) IL_0012: ldc.i4.0 IL_0013: ceq IL_0015: stloc.2 IL_0016: ldloc.2 IL_0017: brtrue.s IL_001f IL_0019: nop IL_001a: ldc.i4.0 IL_001b: stloc.0 IL_001c: nop IL_001d: br.s IL_0023 IL_001f: nop IL_0020: ldc.i4.1 IL_0021: stloc.0 IL_0022: nop IL_0023: ldloc.1 IL_0024: ldstr "not" IL_0029: call bool [mscorlib]System.String::op_Equality(string, string) IL_002e: brtrue.s IL_0033 IL_0030: ldc.i4.1 IL_0031: br.s IL_0034 IL_0033: ldc.i4.0 IL_0034: nop IL_0035: stloc.0 IL_0036: ret } // end of method



你可以通过一些指令看到三元部分更短......原因是if语句引入了一个局部变量仅在if块内部使用。

这种差异会让你获得一点点性能,恕我直言,如果不适合使用三元替换,我不能证明这一点!


You can see that the ternary part shorter by a few instructions...The reason is that if statement is introducing a local variable to use only inside the if block.
This difference will gain you a tiny bit of performance, that IMHO do not justify to use ternary replace if when it's not fit!


这篇关于三元运算符?:vs if ... else ..哪一个更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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