Performance: condition testing vs assignment

99封情书 提交于 2019-12-06 07:49:25

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

This could be better, depending on what condition actually is:

if (condition) {

    //execute first run code

    while (condition) {
        //execute subsequent run code
    }
}

Given your example, you don't need the extra variable.

You don't even need the if statement if you know the code will always run at least once:

//execute first run code

while (condition) {
    //execute subsequent run code
}
<?php

class Test
{
    private $var = 156135135;
    const SOMETHING = 156135135;

    public function assign()
    {
        $this->var = self::SOMETHING;
    }

    public function conditionalAssign()
    {
        if ($this->var != self::SOMETHING) {
            $this->var = SELF::SOMETHING;
        }
    }

}

$obj = new Test;

$start = microtime(true);
for ($i = 1; $i < 10000000; ++$i) {
    $obj->assign();
}
echo round((microtime(true) - $start) * 1000, 2).' ms'.PHP_EOL;

$start = microtime(true);
for ($i = 1; $i < 10000000; ++$i) {
    $obj->conditionalAssign();
}
echo round((microtime(true) - $start) * 1000, 2).' ms'.PHP_EOL;

conditionalAssign always faster when variable is integer, often faster when variable is boolean and almost equal, when variable is string.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!