三元?运营商VS C#中的传统的if-else运营商 [英] Ternary ? operator vs the conventional If-else operator in c#

查看:161
本文介绍了三元?运营商VS C#中的传统的if-else运营商的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
是条件运算慢?

我是在的海量用户?运算符在C#。但是我的项目经理经常警告我说,使用运营商可能比作在的if-else 语句花费一些性能大规模应用。所以我告诉避免使用它。然而,在使用时,我喜欢使用它,因为它简洁排序保持代码的清洁。

I'm a massive user of the ? operator in C#. However my project manager frequently warns me that using ? operator might cost some performance compared to the If-Else statements in a large scale application. So I'm told to avoid using it. However, I love using it because it is concise and sort of keeps the code clean.

会出现这样的性能开销运营商?

Is there such performance overhead when using ? operator?

推荐答案

我跑亿三元运算1亿if-else语句,并记录每个性能。下面是代码:

I ran 100 million Ternary Operators and 100 million If-Else statements and recorded the performance of each. Here is the code:

Stopwatch s = new Stopwatch();
// System.Diagnostics Stopwatch
int test = 0;
s.Start();
for(int a = 0; a < 100000000; a++)
    test = a % 50 == 0 ? 1 : 2;
s.Stop();

s.Restart();
for(int b = 0; b < 100000000; b++)
{
    if(b % 50 == 0)
        test = 1;
    else
        test = 2; 
}
s.Stop();

下面是结果(运行在英特尔Atom 1.66GHz的1GB内存,我知道,它吮吸):

Here is the results (ran on an Intel Atom 1.66ghz with 1gb ram and I know, it sucks):


  • 三元接线员:5986毫秒或每各运营商0.00000005986秒

  • Ternary Operator: 5986 milliseconds or 0.00000005986 seconds per each operator.

如果-ELSE:5667毫秒或每每条语句0.00000005667秒

If-Else: 5667 milliseconds or 0.00000005667 seconds per each statement.

不要忘了,我跑亿人,而我不认为两者之间的问题0.00000000319秒差那么多。

Don't forget that I ran 100 million of them, and I don't think 0.00000000319 seconds difference between the two matters that much.

这篇关于三元?运营商VS C#中的传统的if-else运营商的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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