三元 ?运算符与 C# 中的传统 If-else 运算符 [英] Ternary ? operator vs the conventional If-else operator in c#

查看:54
本文介绍了三元 ?运算符与 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.

使用时有这样的性能开销吗?操作符?

推荐答案

我运行了 1 亿个三元运算符和 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();

这是结果(在 Intel Atom 1.66ghz 和 1gb ram 上运行,我知道,这很糟糕):

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.

If-Else:每条语句 5667 毫秒或 0.00000005667 秒.

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

别忘了我跑了 1 亿次,我不认为两者之间的 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.

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

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