Hacker News new | ask | show | jobs
by conradfr 4079 days ago
> Some people also don't understand that arrays of large data have to be wrapped in objects or explicitly passed by reference in many situations to avoid duplicating them in memory.

IIRC arrays are always passed by reference and only duplicated if you modify the data inside the called function (if not passed with '&' of course) ?

2 comments

Correct. The runtime uses a copy-on-write implementation when you pass an array by value.

Duplicating an array in memory every time it is passed to or from a function would be awful.

> Duplicating an array in memory every time it is passed to or from a function would be awful.

This might be because I originally learned PHP about 16 years ago, but I could swear this used to be the case. There's definitely a reason PHP has the reputation it has, although many of those glaring issues have since been fixed.

I started with PHP3 and also didn't know or care about that for a long time. Then Doctrine with its hydrators and PHP daemons became a thing in the workplace and all of sudden you have to be a bit more careful with data size and memory management.
Call-time pass-by-reference (passing with '&') has been either deprecated or removed. It has to be done in the function signature.

> only duplicated if you modify the data inside the called function

I did not know that. Because I've observed the duplication behavior, I assumed that it was never a reference. I guess that's a "feature" when you don't really have any fine-grained, explicit control over pointers or references.