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

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

它说

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()运行了你的代码,并且内存消耗没有任何差异(但是这并不一定意味着什么,当一个人真的在做一些变量时,内存消耗可能不同)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值