三元 ?运算符与 C# 中的传统 If

编程入门 行业动态 更新时间:2024-10-27 00:33:36
本文介绍了三元 ?运算符与 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

本文发布于:2023-11-07 22:24:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1567603.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:运算符   传统

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!