Skip to content

Instantly share code, notes, and snippets.

@ludofleury
Created January 31, 2012 04:21
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ludofleury/1708784 to your computer and use it in GitHub Desktop.
Save ludofleury/1708784 to your computer and use it in GitHub Desktop.
PHP get_class vs ReflectionObject vs ReflectionClass
This was a quick & dirty benchmark (for my own needs) to compare the method to get a class name in PHP
-ReflectionObject->getName();
-get_class();
-ReflectionClass->getName();
It was performed on my local machine : MacBookPro with PHP 5.3.6
You will find the result below and the code used for the 3 tests.
ReflectionObject
Memory : 750040
Memory peak : 778752
Time : 0.0341 ~ 0.0337
-----------------------
get_class
Memory : 750048
Memory peak : 778760
Time : 0.0340 ~ 0.0332
-----------------------
ReflectionClass
Memory : 750032
Memory peak : 778744
Time : 0.0341 ~ 0.0342
<?php
$object = new Mock\Document();
$time_start = microtime(true);
for($i = 0; $i < 10000; $i++) {
get_class($object);
}
$time_end = microtime(true);
echo 'Memory : '.memory_get_usage()."\n";
echo 'Memory peak : '.memory_get_peak_usage()."\n";
$time = $time_end - $time_start;
echo 'Time : '.$time."\n";
<?php
$object = new Mock\Document();
$time_start = microtime(true);
for($i = 0; $i < 10000; $i++) {
$reflectedObject = new \ReflectionClass('Mock\Document');
$reflectedObject->getName();
}
$time_end = microtime(true);
echo 'Memory : '.memory_get_usage()."\n";
echo 'Memory peak : '.memory_get_peak_usage()."\n";
$time = $time_end - $time_start;
echo 'Time : '.$time."\n";
<?php
$object = new Mock\Document();
$time_start = microtime(true);
for($i = 0; $i < 10000; $i++) {
$reflectedObject = new \ReflectionObject($object);
$reflectedObject->getName();
}
$time_end = microtime(true);
echo 'Memory : '.memory_get_usage()."\n";
echo 'Memory peak : '.memory_get_peak_usage()."\n";
$time = $time_end - $time_start;
echo 'Time : '.$time."\n";
@panvid
Copy link

panvid commented Mar 27, 2018

Performance for newer PHP (7.2.3):

FYI: The get_class method misses to explode the unqualified class name from name with namespace. I added this:

[...]
for($i = 0; $i < 10000; $i++) {
    $name = explode("\\", get_class($object));
    $className = end($name);
}
[...]

get_class

Memory: 384768
Memory peak: 419312
Time: 0.0024218559265137

ReflectionClass

Memory: 384664
Memory peak: 419224
Time: 0.0073721408843994

ReflectionObject

Memory: 384664
Memory peak: 419232
Time: 0.0038409233093262

@rask
Copy link

rask commented Jul 31, 2019

With newer PHP versions \hrtime() will probably offer more accurate measurements than \microtime().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment