性能:if else vs switch,while vs for,每个vs for,print vs printf [英] Performance: if else vs switch, while vs for, for each vs for, print vs printf

查看:124
本文介绍了性能:if else vs switch,while vs for,每个vs for,print vs printf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用getrusage()测试所有这些不同的构造,以计算(ru_utime + ru_stime)在执行它们之前和之后的变化.
事实证明,对于类似的构造执行相同的任务并没有什么不同.结果如下: printf(1.5± 0.5)%比print
foreach(6.0± 1.0)%比for循环快(迭代索引数组) 1kk个元素)
forwhile循环快(9.0±1.0)%
if/elseswitch快(8.0±1.0)%(已在两个案例中进行了测试,6个案例,以及10种可能的情况).

I was testing all these different constructs using getrusage() to calculate the variations of (ru_utime + ru_stime) before and after executing them.
It turns out there's no little difference in performing the same task for similar constructs. Here are the results:
printf (1.5 ± 0.5)% faster than print
foreach (6.0 ± 1.0)% faster than a for loop(iterating over an indexed array of 1kk elements)
for (9.0 ± 1.0)% faster than a while loop
if/else (8.0 ± 1.0)% faster than a switch(tested over two cases, 6 cases, and 10 possible cases).

所以我想知道,这些差异真的重要吗?如果我们在代码中使用所有最高效的此类构造,会有所不同吗?总结6%,8%,9%或10%可能会改变我们的代码效率?或者这些差异还是不明显,我的意思是服务器对请求的响应几乎不会改变?另外,如果我们在switch上使用if/else,在while上使用for,在print上使用printf,在for上使用foreach,会占用更多的RAM吗?

So I was wondering, do these differences really matter? If we use all the most efficient such constructs in our code, will it make some difference? Maybe 6%, 8% there, 9% or 10% there, summed up will change the efficiency of our code?
Or will these differences nonetheless be not noticeable, I mean the response of the server to requests will almost not vary? Also, if we use if/else over switch, for over while, printf over print, foreach over for, will it eat up more RAM?

推荐答案

就性能而言,使用StackOverflow答案回答问题:

Answering your question using StackOverflow answers, in terms of performance:

对于if/elseswitch:性能相同(

For if/else vs switch: Same performance (more).

对于forforeachwhile:没关系(

For for vs foreach vs while: It doesn't matter (more).

对于printfprint:一个不比另一个好(更多 ).

For printf vs print: One not better than the other (more).

我的拙见是,您使用看起来更舒适和/或更好地满足您的需求的产品(彼此之间在性能方面还存在细微的差异,这取决于您的需求).在性能方面,为了使性能最大化,您还需要注意其他事项,例如降低程序中使用的代码的O复杂度,网络延迟处理,需要时并行执行任务等.您的问题是有点一般,所以我试图用同样的方式回答.

My humble opinion is that you use whatever seems more comfortable to you and/or covers your needs better (there are slight differences between each other, in other terms than performance, and this depends on what you need). In terms of performance, there are other things that you should take care of in order to maximize performance, such as decreasing the O complexity of code used in your program, network delays handling, parallelization of tasks when needed etc. Your question is a little bit general, so I tried to answer the same way.

这篇关于性能:if else vs switch,while vs for,每个vs for,print vs printf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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