Is Pass-by-Reference Always Faster in PHP?

Susan Sarandon
Release: 2024-11-08 18:02:02
Original
901 people have browsed it

Is Pass-by-Reference Always Faster in PHP?

Is Passing by Reference Faster in PHP (>=5.0)?

Despite the primary purpose of pass-by-reference in PHP being variable manipulation outside the function's scope, one might speculate if it also affects performance. PHP employs Copy On Write to optimize object and array copying, which should eliminate the need for pass-by-reference for parameters that remain unchanged.

Performance Comparison

To determine the performance impact, an experiment was conducted with 100,000 function calls, passing a 20 kB string as a parameter. Two scenarios were tested:

  1. Function that reads/uses the parameter
  2. Function that writes/modifies the parameter

Results

  • Pass by Value vs. Reference for Reading/Using Parameters:

    • Pass by value: 0.12065005 seconds
    • Pass by reference: 1.52171397 seconds
  • Pass by Value vs. Reference for Writing/Modifying Parameters:

    • Pass by value: 1.52223396 seconds
    • Pass by reference: 1.52388787 seconds

Conclusions

  1. Passing by value is consistently faster than pass-by-reference.
  2. For functions that modify the parameter's value, there is no practical performance difference between pass-by-value and pass-by-reference.

The above is the detailed content of Is Pass-by-Reference Always Faster in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template