1

In C++ passing variables from functions to the function caller can always have better performance when returning a variable by const & (constant reference).

class A {
    private:
    std::string name;
    public:
    inline const std::string& getName() { return this->name; } const
}

I am wondering if returning variables from a function in PHP as a reference can have better performance then just returning a variable like normal.

In C++ I understand that when you return a variable without const ref it copies the data into the variable that you are setting it to. So you will have two locations in memory with the same data.

But when you pass around references, you are just passing the address in memory to the same data.

Is this how it works in PHP? Or does PHP do optimization regardless?

Will the following function run faster if it is written like so? Returning a reference?

public function &getDatabaseConnection() { return $this->databaseConnection; }

Or does it not make much of a difference?

Keith Becker
  • 556
  • 1
  • 6
  • 16
  • 1
    Irrelevant in comparison to the database interactions. And, no. – mario Jun 13 '19 at 16:02
  • 1
    The references in PHP work differently. Don't use them unless you have to. PHP uses CoW so the performance would be presumably slightly better without using references. – Dharman Jun 13 '19 at 16:08
  • Don't worry about this unless it's actually causing a performance problem. [Premature optimization is the root of all evil](http://c2.com/cgi/wiki?PrematureOptimization). Most of the time the difference is negligible. Write it in the way that's most clear to the reader, worry about performance later if necessary. – Barmar Jun 13 '19 at 16:16
  • @Barmar I have written the php script without worrying about performance following much of the same reasons you pointed out. However, I am hitting a performance barrier now. I have a script that is pulling data from an API and storing this data in a database. I have to retrieve around 600,000 pieces of data from this external api. My script was processing this data around 10 pieces of data per .25 seconds yesterday. I let it continue running thought the night. Now it is processing the data at about 2 pieces of data / second. So I am looking for the performance bottlenecks now. – Keith Becker Jun 13 '19 at 16:31
  • OK, then I'll reiterate what @Dharman said. PHP uses copy-on-write when you assign and return data, so it doesn't make copies unnecessarily. – Barmar Jun 13 '19 at 16:34

0 Answers0