Last active
June 26, 2025 10:55
-
-
Save KVytyagov/57509333daaac69eb980777c7d28ea18 to your computer and use it in GitHub Desktop.
performance instanceof vs eq(null)
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 | |
| $iterations = 10**6; | |
| class SomeVeryLongNameForCompareWithSomeVeryPerfectMethodOrStrategyAndSomeOtherWordsInThisName {} | |
| class Short{} | |
| function checkInstanceOfLongClassName($val): bool { | |
| return $val instanceof SomeVeryLongNameForCompareWithSomeVeryPerfectMethodOrStrategyAndSomeOtherWordsInThisName; | |
| } | |
| function checkInstanceOfShortClassName($val): bool { | |
| return $val instanceof Short; | |
| } | |
| function nullEquality($val): bool { | |
| return $val === null; | |
| } | |
| $testFunctions = [ | |
| 'checkInstanceOfLongClassName', | |
| 'checkInstanceOfShortClassName', | |
| 'nullEquality', | |
| ]; | |
| $checkedValues = [ | |
| 'null' => null, | |
| 'shortClassName' => new Short(), | |
| 'longClassName' => new SomeVeryLongNameForCompareWithSomeVeryPerfectMethodOrStrategyAndSomeOtherWordsInThisName(), | |
| ]; | |
| foreach ($testFunctions as $functionName) { | |
| foreach ($checkedValues as $valueName => $value) { | |
| $results = []; | |
| for($i = 0; $i < $iterations; ++$i) { | |
| $start = microtime(true); | |
| $memoryPeakOnStart = memory_get_peak_usage(true); | |
| $res = $functionName($value); | |
| $time = microtime(true) - $start; | |
| $memoryPeakIncrease = memory_get_peak_usage(true) - $memoryPeakOnStart; | |
| $results['times'][] = $time; | |
| $results['memoryPeak'][] = $memoryPeakIncrease; | |
| } | |
| echo sprintf( | |
| "Method '%s' for '%s' \n\tavgTime: %f\n\tavgMemoryPeak: %d\n\tminTime: %d\n\tmaxTime: %d\n", | |
| $functionName, | |
| $valueName, | |
| array_sum($results['times']) / count($results['times']), | |
| array_sum($results['memoryPeak']) / count($results['memoryPeak']), | |
| min($results['times']), | |
| max($results['times']) | |
| ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
output: