Created
October 4, 2014 17:41
-
-
Save jm42/d121f840abbf821d196f to your computer and use it in GitHub Desktop.
Benchmark `method_exists`
This file contains hidden or 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 | |
| include 'Benchmark.php'; // https://github.com/BruceJillis/Benchmark | |
| class Author { | |
| public $firstName; | |
| protected $lastName; | |
| public function __construct($firstName, $lastName) { | |
| $this->firstName = $firstName; | |
| $this->lastName = $lastName; | |
| } | |
| public function getLastName() { | |
| return strtoupper($this->lastName); | |
| } | |
| } | |
| $author = new Author('John', 'Doe'); | |
| // --------------------------------------------------------------------------- | |
| $benchmark = new Benchmark(); | |
| $benchmark->start('get_class_methods'); | |
| for ($i = 0; $i < 10000000; $i++) { | |
| in_array('getLastName', get_class_methods($author)); | |
| } | |
| $benchmark->stop('get_class_methods'); | |
| $benchmark->start('method_exists'); | |
| for ($i = 0; $i < 10000000; $i++) { | |
| method_exists($author, 'getLastName'); | |
| } | |
| $benchmark->stop('method_exists'); | |
| $benchmark->start('static method_exists'); | |
| for ($i = 0; $i < 10000000; $i++) { | |
| method_exists('Author', 'getLastName'); | |
| } | |
| $benchmark->stop('static method_exists'); | |
| $benchmark->start('is_callable'); | |
| for ($i = 0; $i < 10000000; $i++) { | |
| is_callable($author, 'getLastName'); | |
| } | |
| $benchmark->stop('is_callable'); | |
| $benchmark->start('static is_callable'); | |
| for ($i = 0; $i < 10000000; $i++) { | |
| is_callable('Author', 'getLastName'); | |
| } | |
| $benchmark->stop('static is_callable'); | |
| $benchmark->start('hasMethod'); | |
| $refclass = new \ReflectionObject($author); | |
| for ($i = 0; $i < 10000000; $i++) { | |
| $refclass->hasMethod('getLastName'); | |
| } | |
| $benchmark->stop('hasMethod'); | |
| $benchmark->start('hasMethod (wo/new)'); | |
| for ($i = 0; $i < 10000000; $i++) { | |
| $refclass->hasMethod('getLastName'); | |
| } | |
| $benchmark->stop('hasMethod (wo/new)'); | |
| $benchmark->display(); | |
| # | time | memory | | |
| # get_class_methods | 31.92 s | 768 B | | |
| # is_callable | 17.29 s | 512 B | | |
| # hasMethod (wo/new) | 16.55 s | 488 B | | |
| # hasMethod | 16.53 s | 832 B | | |
| # static method_exists | 16.51 s | 488 B | | |
| # static is_callable | 15.45 s | 488 B | | |
| # method_exists | 15.34 s | 488 B | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment