PHP Performance : Copy vs. Reference

后端 未结 6 1448
南旧
南旧 2021-01-18 02:26

Hey there. Today I wrote a small benchmark script to compare performance of copying variables vs. creating references to them. I was expecting, that creating references to l

6条回答
  •  爱一瞬间的悲伤
    2021-01-18 03:12

    You don't need to (and thus shouldn't) assign or pass variables by reference just for performance reasons. PHP does such optimizations automatically.

    The test you ran is flawed because of these automatic optimizations. In ran the following test instead:

    \n";
    
    $time = microtime(1);
    for($i=0; $i<1000; $i++) {
        $copy =& $array;
        unset($copy);
    }
    $duration = microtime(1) - $time;
    echo "Assignment by Reference and don't write: $duration
    \n"; $time = microtime(1); for($i=0; $i<1000; $i++) { $copy = $array; $copy[0] = 0; unset($copy); } $duration = microtime(1) - $time; echo "Normal Assignment and write: $duration
    \n"; $time = microtime(1); for($i=0; $i<1000; $i++) { $copy =& $array; $copy[0] = 0; unset($copy); } $duration = microtime(1) - $time; echo "Assignment by Reference and write: $duration
    \n"; ?>

    This was the output:

    //Normal Assignment without write: 0.00023698806762695
    //Assignment by Reference without write: 0.00023508071899414
    //Normal Assignment with write: 21.302103042603
    //Assignment by Reference with write: 0.00030708312988281
    

    As you can see there is no significant performance difference in assigning by reference until you actually write to the copy, i.e. when there is also a functional difference.

提交回复
热议问题