Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

performance - In PHP (>= 5.0), is passing by reference faster?

In PHP, function parameters can be passed by reference by prepending an ampersand to the parameter in the function declaration, like so:

function foo(&$bar)
{
    // ...
}

Now, I am aware that this is not designed to improve performance, but to allow functions to change variables that are normally out of their scope.

Instead, PHP seems to use Copy On Write to avoid copying objects (and maybe also arrays) until they are changed. So, for functions that do not change their parameters, the effect should be the same as if you had passed them by reference.

However, I was wondering if the Copy On Write logic maybe is shortcircuited on pass-by-reference and whether that has any performance impact.

ETA: To be sure, I assume that it's not faster, and I am well aware that this is not what references are for. So I think my own guesses are quite good, I'm just looking for an answer from someone who really knows what's definitely happening under the hood. In five years of PHP development, I've always found it hard to get quality information on PHP internals short from reading the source.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In a test with 100 000 iterations of calling a function with a string of 20 kB, the results are:

Function that just reads / uses the parameter

pass by value:      0.12065005 seconds
pass by reference:  1.52171397 seconds

Function to write / change the parameter

pass by value:      1.52223396 seconds
pass by reference:  1.52388787 seconds

Conclusions

  1. Pass the parameter by value is always faster

  2. If the function change the value of the variable passed, for practical purposes is the same as pass by reference than by value


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...