在涉及到计算数字的奇偶是,一般都用到“与”运算和“模运算”,那么这两种运算用PHP语言来实现的话,哪个更快呢?在比较前,我是倾向于前者的。但结果却让我很诧异。代码如下:

“与”运算:

<?php
set_time_limit(0);
$i = 1;
$t1 = microtime(true);
while($i < 1000000001){
$i ++ & 1;
}
$t2 = microtime(true);
echo $t2 - $t1;

结果:wKioL1Zid_Hzm_AhAAAEP29JfQc592.png

“模”运算:

<?php
set_time_limit(0);
$i = 1;
$t1 = microtime(true);
while($i < 1000000001){
$i ++ % 2;
}
$t2 = microtime(true);
echo $t2 - $t1;

结果:wKiom1Zid_aS9b4_AAAEoMEHkRM261.png