php返回变量累加,PHP: 递增/递减运算符 - Manual

When using the ++ operator by itself on a variable, ++$var is faster than $var++ and uses slightly less memory (in my experiments).  It would seem like this could be optimized in the language during runtime (if $var++ is the only thing in the whole statement, it could be treated as ++$var).

I conducted many tests (I believe to be fair), and here's one of the results:

$i++ took 8.47515535355 seconds and 2360 bytes

++$i took 7.80081486702 seconds and 2160 bytes

Here's my code.  If anyone sees a bias in it, tell me.  I conducted it many times, each time going through a loop one million iterations and doing each test 10 - 15 times (10 - 15 million uses of the ++ operator).

ini_set('MAX_EXEC_TIME',120);ob_start( );$num_tests=10;$startFirst=$startSecond=$endFirst=$endSecond=$startFirstMemory=$endFirstMemory=$startSecondMemory=$endSecondMemory=$someVal=0;$times= array('$i++'=> array('time'=>0,'memory'=>0),'++$i'=> array('total'=>0,'memory'=>0) );

for($j=0;$j

{

for($i=0,$startFirstMemory=memory_get_usage( ),$startFirst=microtime(true);$i<10000000;$i++ ){$someval=2; }$endFirstMemory=memory_get_usage( );$endFirst=microtime(true);

for($i=0,$startSecondMemory=memory_get_usage( ),$startSecond=microtime(true);$i<10000000; ++$i){$someval=2; }$endSecondMemory=memory_get_usage( );$endSecond=microtime(true);$times['$i++'][$j] = array('startTime'=>$startFirst,'endTime'=>$endFirst,'startMemory'=>$startFirstMemory,'endMemory'=>$endFirstMemory);$times['++$i'][$j] = array('startTime'=>$startSecond,'endTime'=>$endSecond,'startMemory'=>$startSecondMemory,'endMemory'=>$endSecondMemory);

}

for($i=0;$i

{$times['$i++']['time'] += ($times['$i++'][$i]['endTime'] -$times['$i++'][$i]['startTime'] );$times['++$i']['time'] += ($times['++$i'][$i]['endTime'] -$times['++$i'][$i]['startTime'] );$times['$i++']['memory'] += ($times['$i++'][$i]['endMemory'] -$times['$i++'][$i]['startMemory'] );$times['++$i']['memory'] += ($times['++$i'][$i]['endMemory'] -$times['++$i'][$i]['startMemory'] );

}

echo'There were '.$num_tests.' tests conducted, here\'s the totals

$i++ took '.$times['$i++']['time'] .' seconds and '.$times['$i++']['memory'] .' bytes

++$i took '.$times['++$i']['time'] .' seconds and '.$times['++$i']['memory'] .' bytes';ob_end_flush( );?>

Try it yourself, ;)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值