php - Why is an empty __set() method slower than one that does work? -


i toying around php magic methods (specifically property overloading), and, while micro-benchmarking, encountered quirk i'm having trouble explaining:

it seems __set method empty body takes more time run 1 work. below code snippet demonstrates this:

class emptysetter {     public function __set($name, $value) {} }  class nonemptysetter {     public function __set($name, $value) {         $this->{$name} = $value;     } }  function benchmark($obj) {     $start_time = microtime(true);     ($i = 0; $i < 10000000; $i++) {         $obj->foo = 42;     }     return microtime(true) - $start_time; }  printf("emptysetter: %.2f seconds\n", benchmark(new emptysetter)); printf("nonemptysetter: %.2f seconds\n", benchmark(new nonemptysetter));  // output (on core 2 duo laptop): // emptysetter: 4.39 seconds // nonemptysetter: 1.28 seconds 

does have explanation why happening?

oh, see it's wrong testing case.

after first loop nonemptysetter has new public property foo. next loops not call __set method @ all, use public property.

class nonemptysetter {     public function __set($name, $value) {         echo 'called once'; // echoed once.         $this->{$name} = $value;     } } 

valid test

class emptysetter {     public function __set($name, $value) {} }  class nonemptysetter {     public function __set($name, $value) {         $this->{$name} = $value;     } }  function benchmark($class_name) {     $start_time = microtime(true);     ($i = 0; $i < 1000000; $i++) {         $obj = new $class_name();         $obj->foo = 42;     }     return microtime(true) - $start_time; }  printf("nonemptysetter: %.2f seconds\n", benchmark('nonemptysetter')); printf("emptysetter: %.2f seconds\n", benchmark('emptysetter')); 

http://3v4l.org/gvtsq

empty setter faster.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

inno setup - TLabel or TNewStaticText - change .Font.Style on Focus like Cursor changes with .Cursor -