Micro-optimization: Assigning constructor properties by reference

Viewed 39

Many years ago I opened the PHP Manual and started reading like if I were a total newbie to the language, reading those chapters that, let's face it, aren't exactly interesting or useful and sometimes are skipped.

And one thing caught my attention in one chapter.

It was written that when assigning a constructor parameter to a property by reference, internally, the same symbol — which I think is a terminology in C — used for the parameter would be used for the property instead of creating a new one just for the assignment:

<?php

class MyClass {

    protected $myProperty;

    public function __construct( $property ) {

        // Here!

        $this -> myProperty =& $property;
    }

    public function getPropertyValue() {
        return $this -> myProperty;
    }
}

Kind of makes sense, after all, the main characteristic of references is to affect a variable of an external scope in a local one. But I never bothered in testing or profiling and I somewhat started doing this on small codes almost by inertia and the case went sleep with the lazy neurons.

But then, recently, this subject appeared in my mind out of my brain limbo (haha) and I ran that fragment of code in 3ev4l, comparing by reference and the usual way to check and, apparently, that really happens.

It's a really small difference — and I ran 100k of times — but it's a curiosity I never got a closure.

Could anyone provide more information, maybe detailed about this? Specifically, but not restricted to, potential problems that this could bring?

0 Answers
Related