2

Why php's string is a value type? It is copied all over the place every time the argument is passed to a function, every time the assignment is made, every concatenation causes string to be copied. My .NET experience tells me that it seems inefficient and forces me to use references almost everywhere. Consider the following alternatives:

Alternative 1

// This implementation hurts performance
class X {
    public $str;
    function __construct($str) { // string copied during argument pass
        $this->$str = $str; // string copied here during assignment
    }
}

Alternative 2

// This implementation hurts security
class Y {
    public $str;
    function __construct(&$str) {
        $this->$str = &$str;
    }
}
// because
$var = 'var';
$y = new Y($var);
$var[0] = 'Y';
echo $y->var; // shows 'Yar'

Alternative 3

// This implementation is a potential solution, the callee decides
// whether to pass the argument by reference or by value, but
// unfortunately it is considered 'deprecated'
class Z {
    public $str;
    function __construct($str) {
        $this->$str = &$str;
    }
}
// but
$var = 'var';
$z = new Z(&$var); // warning jumps out here
$var[0] = 'Z';
echo $y->var; // shows 'Zar'

The question: What pain should I choose Performance / Security / Deprecation

Lu4
  • 14,873
  • 15
  • 79
  • 132
  • 1
    Seriously? It hurts performance? Let me tell you that using references everywhere will hurt performance even more in PHP. – BoltClock Dec 30 '10 at 19:22
  • 1
    Unless you are initializing a million objects or passing over huge amounts of data in the argument, performance is a total non-issue here. Can you show a real world example of what you are doing? – Pekka Dec 30 '10 at 19:22
  • Okay, can I suppose then that you put all images in a single file and compressed it to serve dinamically and use css sprites, and everything that is not micro-performance before, right? Also, if there is a real case where this can be a performance issue, I can't understand why not use a real powerful language such C++. – Davis Peixoto Dec 30 '10 at 19:41

2 Answers2

10

PHP handle's it's variables pretty reasonably. Internally, PHP uses a copy-on-modification system.

That is to say that those values will be assigned by reference until one of them is changed, in which case it will get a new slot in memory for the new value.

Craige
  • 2,882
  • 2
  • 20
  • 28
1

Passing vars by reference is going to hurt performance.

Your example #1 is the best performance and best way to go about it.

class X {
    public $str;
    function __construct($str) {
        $this->str = $str;
    }
}
Dreamcube
  • 165
  • 1
  • 10