性能:条件测试与分配 [英] Performance: condition testing vs assignment

查看:63
本文介绍了性能:条件测试与分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个循环,其中使用变量测试循环的当前遍历是否为第一个。相当简单:

  $ firstrun = true; 
while(condition){
if($ firstrun)
//这样做
else
//这样做

//更改$ firstrun为假
}

我只是想知道(主要是出于好奇,因为我m并没有什么明显的不同),当我需要将 $ firstrun 更改为false时,测试变量是否为 true <会更有效。 / code>,然后在每次执行过程中将其分配为false还是将其重新分配为false?



Ex:

  $ firstrun = true; 
while(condition){
if($ firstrun)
//这样做
else
//做到

if($ firstrun)
$ firstrun = false;
}

或简单地

  $ firstrun = true; 
while(condition){
if($ firstrun)
//执行
else
//执行

$ firstrun =假;
}

PS:
我想这也是一个不好的例子,因为将 $ firstrun 的重新分配放入原始状态将是最有效的,但是正如我说的那样,出于好奇,我想只是假装那不是一个选择出于某种原因。



PSS:
当这个主意击中我时,我正在用PHP进行编码,但是我猜测该解决方案与语言无关。只是以为我会把它扔在那里,以防万一它由于某种原因而起作用。 strong>

解决方案

以上都不是

  $ firstrun = true; 
while(condition)
{
if($ firstrun)
{
$ firstrun = false;
}
其他
{
}
}

我之所以这样说,是因为您反复将false分配给 $ firstrun ,您应该在第一个循环中这样做



条件测试与分配相比,哪个更快?



例如,是相同的(一个执行周期没有一些昂贵的通话)



已更新



我认为条件测试会比较慢,因为在此之后您可能会调用一系列后续操作


I've created a loop where a variable is used to test if the current run-through of the loop is the first one. Its fairly simple:

$firstrun = true;
while(condition){
  if($firstrun)
    // Do this
  else
    // Do that

  // Change $firstrun to false
}

I was just wondering (mostly out of curiosity because I'm it makes no real noticeable difference), when I need to change $firstrun to false, would be more efficient to test if the variable is true before assigning it to false or simply reassign it to false during each run-through?

Ex:

$firstrun = true;
while(condition){
  if($firstrun)
    // Do this
  else
    // Do that

  if($firstrun)
    $firstrun = false;
}

or simply

$firstrun = true;
while(condition){
  if($firstrun)
    // Do this
  else
    // Do that

  $firstrun = false;
}

PS: I guess this is a bad example also, because it would be most efficient to throw the reassignment of $firstrun in with the original condition, but as I said this is out of curiosity so I guess just pretend that is not an option for some reason.

PSS: I was coding in PHP when this idea hit me, but I'm guessing the solution would be language agnostic. Just thought I would throw that in there in case it does for some reason matter.

So ultimately, which is faster, condition testing or variable assignment?

解决方案

none of the above

$firstrun = true;
while(condition)
{
  if($firstrun)
  {
    $firstrun = false;
  }
  else
  {
  }
}

reason I said so, because you are repetitively re-assign false to $firstrun, which you should just do at the first loop

condition test vs assignment which is faster?

for example you have shown, is the same (one execution cycle without some expensive call)

updated

I think condition testing will be slower, cause you might invoke series of subsequent action after that

这篇关于性能:条件测试与分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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