gpt4 book ai didi

php - 在 php 函数中引用变量是否有助于节省内存?

转载 作者:IT王子 更新时间:2023-10-28 23:57:29 26 4
gpt4 key购买 nike

例如,当比较内存的管理方式时,以下两个函数是否相同:

$hello = 'hello';

my_echo($hello);

//Better or worse than
my_echo_ref($hello);

//case 1, no referencing:
function my_echo($word) {
echo $word;
}

//case 2, referencing:
function my_echo_ref(&$word) {
echo $word;
}

最佳答案

我不知道这个来源有多可靠,但这是一篇非常有趣的文章(自 2008 年起)解释了如何处理变量:

The Truth About PHP Variables

它说

I wanted to write this post to clear up what seems to be a common misunderstanding in PHP – that using references when passing around large variables is a good way save memory.

(...) While the above explanation of references is sufficient for a general understanding, it is often useful to understand how PHP handles variable assignment internally. This is where we introduce the concept of the zval.

zvals are an internal PHP structure which are used for storing variables. Each zval contains various pieces of information, and the ones we will be focusing on here are as follows:

  • The actual data stored within the zval – In our example this would be either ‘hello!’ or ‘goodbye!’
  • is_ref Boolean flag
  • A ref_count counter

(...)

(...) When you assign a variable by value (such as in example 1) it does not create a new zval, it simply points both variables at the same zval and increases that zval’s ref_count by one. “Wait!” I hear you cry, “Isn’t that passing by reference?” Well, although it sounds the same, all PHP is doing is postponing any copying until it really has to – and it knows this because is_ref is still false. (...)

结论:

You can see that, unless the developer is completely consistent, passing variables by reference can easily lead to increased memory usage.


除此之外,我用 get_memory_usage() 运行了你的代码几次,内存消耗没有差异(但这并不一定意味着什么,可能内存消耗在实际情况下有所不同用变量做点什么)。

关于php - 在 php 函数中引用变量是否有助于节省内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3126013/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com