So, instead of doing something like this:
Code: Select all
Class::instance()->foo = $bar;Code: Select all
Class::$foo = $bar;To test I wrote a simple script with two different classes, which you can see below. Granted, this is a very simple implementation, but the class using no instantiation and only late static binding performed more than 1 second better than the singleton class on each one of my tests. This is pretty significant.
Code: Select all
class Foo {
protected static $var;
public static function set($var) {
static::$var = $var;
}
public static function get() {
return static::$var;
}
}
class Bar {
protected static $_instance;
protected $var;
public static function instance() {
if(!static::$_instance) {
static::$_instance = new static;
}
return static::$_instance;
}
public function set($var) {
$this->var = $var;
}
public function get() {
return $this->var;
}
}
$start = microtime(true);
for($i=0;$i<100000;$i++) {
Bar::instance()->set($i);
$n = Bar::instance()->get($i);
//Foo::set($i);
//$n = Foo::get($i);
}
$end = microtime(true);
echo 'Time: '.($end - $start);Foo: .98975, .97701, .98959, .98653, .99109
Bar: 2.19747, 2.18299, 2.22071, 2.19148, 2.19010
Now you might say, well yeah, there's an extra step in there, the singleton class has to first grab the instance and then do its business. But that is the case in all implementations of these design patterns. With the traditional singleton, there will always be that extra step in accessing the instance before doing anything else.
So my question is, say this is a more complex class that does more than just getting and setting. Now that we can set static class properties at runtime using late static runtime, can you foresee any event in which object instantiation is REQUIRED in order to perform a certain function? In the past, the only reason why I used the traditional singleton design pattern was because I needed to set properties at runtime; now that I can do that for static class properties, I can't see any reason why I would use that design pattern anymore. Also, could the performance difference be mitigated by a more complex class?
Thoughts?