Last active
February 25, 2023 12:48
-
-
Save PatelUtkarsh/8001d763a0012c3706b1d092204243c5 to your computer and use it in GitHub Desktop.
Compare performance of class_implements vs implementsInterface (using ReflectionClass) for 1,00,000 class.
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 | |
// Define an interface | |
interface MyInterface { | |
public function myFunction(); | |
} | |
// Define 1000 classes that implement the interface | |
for ($i = 1; $i <= 100000; $i++) { | |
$className = 'MyClass' . $i; | |
eval(" | |
class $className implements MyInterface { | |
public function myFunction() { | |
// Do something | |
} | |
} | |
"); | |
} | |
// Define a function to check if a class implements the interface using class_implements() | |
function check_implements($class) { | |
if (class_exists($class)) { | |
return in_array('MyInterface', class_implements($class)); | |
} else { | |
return false; | |
} | |
} | |
// Define a function to check if a class implements the interface using ReflectionClass | |
function check_reflection($class) { | |
if (class_exists($class)) { | |
$reflection = new ReflectionClass($class); | |
return $reflection->implementsInterface('MyInterface'); | |
} else { | |
return false; | |
} | |
} | |
// Generate an array of class names to test | |
$classes = array(); | |
for ($i = 1; $i <= 100000; $i++) { | |
$classes[] = 'MyClass' . $i; | |
} | |
// Test the performance of the check_implements() function | |
$start = microtime(true); | |
foreach ($classes as $class) { | |
check_implements($class); | |
} | |
$end = microtime(true); | |
$duration_implements = ($end - $start) * 1000; | |
echo "check_implements() duration: $duration_implements ms\n"; | |
// Test the performance of the check_reflection() function | |
$start = microtime(true); | |
foreach ($classes as $class) { | |
check_reflection($class); | |
} | |
$end = microtime(true); | |
$duration_reflection = ($end - $start) * 1000; | |
echo "check_reflection() duration: $duration_reflection ms\n"; |
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
# On M1 machine - base model. | |
check_implements() duration: 43.645858764648 ms | |
check_reflection() duration: 56.891918182373 ms |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment