Created
December 23, 2010 07:20
-
-
Save sethwalker/752693 to your computer and use it in GitHub Desktop.
testing reflection overhead
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class HasMagicMethods { | |
protected function protectedFoo() { | |
return "called protected method"; | |
} | |
public function __call($name, $arguments) { | |
return "called magic method $name"; | |
} | |
} | |
class HasMagicMethodsAndThrowsExceptions { | |
protected function protectedFoo() { | |
return "called protected method"; | |
} | |
public function __call($name, $arguments) { | |
try { | |
$reflector = new ReflectionMethod($this, $name); | |
if($reflector->isProtected()) { | |
throw new MagicProtectionException('protected method called'); | |
} | |
if($reflector->isPrivate()) { | |
throw new MagicProtectionException('private method called'); | |
} | |
} catch(ReflectionException $e) { | |
} | |
return "called magic method $name"; | |
} | |
} | |
class MagicProtectionException extends Exception { } | |
if($argv) { | |
$does_not_throw = new HasMagicMethods(); | |
$time_start = microtime(true); | |
for($i = 0; $i < 10000; $i++) { | |
$does_not_throw->protectedFoo(); | |
try { | |
throw new Exception(); | |
} catch (Exception $e) { } | |
try { | |
throw new Exception(); | |
} catch (Exception $e) { } | |
} | |
$time_end = microtime(true); | |
$non_throwing_time = ($time_end - $time_start) / 10000.0; | |
print "non-throwing foo: $non_throwing_time\n"; | |
$throws = new HasMagicMethodsAndThrowsExceptions(); | |
$time_start = microtime(true); | |
for($i = 0; $i < 10000; $i++) { | |
try { | |
$throws->protectedFoo(); | |
} catch(MagicProtectionException $e) { | |
} | |
} | |
$time_end = microtime(true); | |
$throwing_time = ($time_end - $time_start) / 10000.0; | |
print "throwing foo: $throwing_time\n"; | |
print "difference: ".($throwing_time - $non_throwing_time)."\n"; | |
return; | |
} | |
class MagicMethodsRaisingExceptionsTest extends PHPUnit_Framework_Testcase { | |
function testMagicMethod() { | |
$o = new HasMagicMethods(); | |
$val = $o->foo(); | |
$this->assertEquals($val, 'called magic method foo'); | |
} | |
/** | |
* @expectedException MagicProtectionException | |
*/ | |
function testProtectedMethodsAndThrowsExceptions() { | |
$o = new HasMagicMethodsAndThrowsExceptions(); | |
$val = $o->protectedFoo(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment