Why does a function return a reference that is slower than the return value? Why is writing a copy slower than a quote?

Source: Internet
Author: User
$array = range(1, 10000);function test1($array){    return $array;}function &test2($array){    return $array;}$start = microtime(true);for ($i=0; $i < 10000; $i++) {     $arr = test1($array);    $arr[$i] = 'new';}$end = microtime(true);echo "Cost ".($end - $start)."\n";$start = microtime(true);for ($i=0; $i < 10000; $i++) {     $arr = test2($array);    $arr[$i] = 'new';}$end = microtime(true);echo "Cost ".($end - $start)."\n";

Output Result:
Cost 5.5163149833679
Cost 6.3323628902435
Although the gap is not big

Reply content:

$array = range(1, 10000);function test1($array){    return $array;}function &test2($array){    return $array;}$start = microtime(true);for ($i=0; $i < 10000; $i++) {     $arr = test1($array);    $arr[$i] = 'new';}$end = microtime(true);echo "Cost ".($end - $start)."\n";$start = microtime(true);for ($i=0; $i < 10000; $i++) {     $arr = test2($array);    $arr[$i] = 'new';}$end = microtime(true);echo "Cost ".($end - $start)."\n";

Output Result:
Cost 5.5163149833679
Cost 6.3323628902435
Although the gap is not big

The copy needs to open up space for initialization and so on, equivalent to creating several new objects.
And a reference is just a pointer.

First, according to the PHP: reference return-Manual explanation, the above two kinds of writing is no different, you can understand that the function without & the underlying engine will be optimized, so it may indeed be a little bit faster, so the manual is not recommended.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.