Skip to content

Instantly share code, notes, and snippets.

@mcuadros
Last active December 15, 2015 05:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcuadros/5212635 to your computer and use it in GitHub Desktop.
Save mcuadros/5212635 to your computer and use it in GitHub Desktop.
How expensive is Reflection usage?

How expensive is Reflection usage?

Result:

  • Reflection 100000 iterations in 2.711766 secs
  • Sort of array(100) 100000 iterations in 1.949580 secs
  • Instance and Method call 100000 iterations in 0.284622 secs

Test code:

<?php
$iterations = $argv[1];

class foo {
  public function bar(array $a, $b, $bar = null, $baz = array('test'), $test = '/') {
    // stuff
  }
}

function reflection() {
    $foo = new ReflectionClass('foo');
    $bar = $foo->getMethod('bar');
    foreach( $bar->getParameters() as $param ) {
        $data['name'] = $param->getName();
        $data['optional'] = $param->isOptional();
        if ( $param->isOptional() ) $data['default'] = $param->getDefaultValue();
    }

    return $data;
}

function sorting() {
    $data = range(0, 100);
    rsort($data);
}

function call() {
    $foo = new foo();
    $foo->bar([], 1);
}

$start = microtime(1);
for($i=0; $i < $iterations; $i++) reflection();
printf('Reflection %d iterations in %3.f secs' . PHP_EOL, $iterations, microtime(true) - $start);

$start = microtime(1);
for($i=0; $i < $iterations; $i++) sorting();
printf('Sort of array(100) %d iterations in %3.f secs' . PHP_EOL, $iterations, microtime(true) - $start);

$start = microtime(1);
for($i=0; $i < $iterations; $i++) call();
printf('Instance and Method call %d iterations in %3.f secs' . PHP_EOL, $iterations, microtime(true) - $start);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment