Last active
January 18, 2022 15:08
-
-
Save tjmoses/800eb9d6e255b3644c6285eae50894e0 to your computer and use it in GitHub Desktop.
PHP 8 vs Node JS Execution Speed (using built in sort)
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 | |
$myArray = []; | |
$arraySize = 100000; | |
for ($i = 0; $i < $arraySize; $i++) { | |
$myArray[$i] = mt_rand(1, 100); | |
} | |
$start = hrtime(true); | |
sort($myArray); | |
$end = hrtime(true); | |
$diff = ($end - $start) / 1000; | |
$phpVersion = phpversion(); | |
echo "PHP ({$phpVersion}) execution time: {$diff} (ms)".PHP_EOL; | |
$jsCode = <<<EOT | |
var myArray = []; | |
for (var i = 0; i <$arraySize; i++) { | |
myArray[i] = Math.random() * 100; | |
} | |
const startTime = process.hrtime.bigint(); | |
myArray.sort(); | |
const endTime = process.hrtime.bigint(); | |
const dur = endTime - startTime; | |
process.stdout.write(dur.toString()); | |
EOT; | |
$nodeVal = shell_exec("node -e '{$jsCode}'") / 1000; | |
$nodeVersion = shell_exec("node -v | tr -d '\n'"); | |
$speedDiff = round($nodeVal / $diff, 2); | |
echo "NodeJS ({$nodeVersion}) execution time: {$nodeVal} (ms)".PHP_EOL; | |
echo "PHP is roughly {$speedDiff} times faster than JS in sorting an array of size ".number_format($arraySize).'!'.PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment