PHP copy on write means ok to pass large arrays by value if read only

While doing a code walkthrough with a fellow devs PHP code I saw that arrays were being passed by reference to functions, not because they needed to be changed but because it would be more performant to pass by reference since the arrays were large and would be copied since passed by value.
It turns out its actually less performant to do this.
PHP will actually not copy arrays by value. PHP uses a "copy-on-write" mechanism which only makes a copy when written to. If your use is just read only then its faster to pass arrays by value, not by reference.
If you want to change the array in the called function then you should pass by reference.

Note: When passed, Objects are passed by reference value i.e. the ref to the object is passed by value, the Object itself is not copied.

Some references

http://www.thedeveloperday.com/php-lazy-copy/

Comments

Popular posts from this blog

deep dive into Material UI TextField built by mui

angular js protractor e2e cheatsheet

react-router v6.4+ loaders, actions, forms and more