duanhuizhe6767 2011-05-23 20:51
浏览 26
已采纳

通过引用返回大数据或作为函数返回?

On the job today I had a argue with a collage about passing large data between scopes. The myth was that reference uses less memory/CPU usage when passing between 2 scopes. We build a proof of concept who was right... so:

function by_return($dummy=null) {
    $dummy = str_repeat("1",100 * 1024 * 1024);
    return $dummy;
}

function by_reference(&$dummy) {
    $dummy = null;
    $dummy = str_repeat("1",100 * 1024 * 1024);
}
echo memory_get_usage()."/".memory_get_peak_usage()."
";
//1 always returns: 105493696/105496656
$nagid = by_return();
echo memory_get_usage()."/".memory_get_peak_usage()."
";
unset($nagid);
//2 always returns:  105493696/210354184 even if we comment 1st part
by_reference($dummy);
echo memory_get_usage()."/".memory_get_peak_usage()."
";
unset($dummy);

But it seems that by reference it consumes more memory according to function "memory_get_peak_usage()"

As you see, using large data for returning is much smarter than using as reference but the question is, why? Any enlightening is welcomed :)

  • 写回答

1条回答 默认 最新

  • douhuang2218 2011-05-23 21:29
    关注

    This is due to the way php handles variables, and is a bit counter-intuitive to anyone who has worked in C or C++.

    Passing by reference to be smarter than PHP isn't advised. PHP doesn't actually make copies of data unless it needs to (i.e. you change a variable's value when there's more than 1 reference to it), an optimization strategy very similar to copy-on-write for shared memory pages.

    So, let's say you have a variable that you pass by value several times in a given script. If you then take this variable and pass it by reference, you're actually duplicating the variable rather than just getting a pointer to the object.

    This is because internally, PHP zvals (the data structure PHP uses to store variables) can only be reference variables or non-reference variables. So it doesn't matter what the zval's ref_count field is, because it's not a reference variable (the is_ref field of the zval structure). So internally, PHP is forced to create a new zval and set its is_ref field to true, thus doubling the memory.

    Tell your co-worker to stop trying to outsmart PHP. Passing by reference unless done 100% perfectly throughout the code will cause a lot of overhead and double the memory usage.

    For a more detailed discussion, please see this link: http://porteightyeight.com/2008/03/18/the-truth-about-php-variables/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 机器学习简单问题解决
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写