Skip to content

Instantly share code, notes, and snippets.

@Jeckerson
Last active August 6, 2020 19:29
Show Gist options
  • Save Jeckerson/46f0dfac8b6333fc9b8e9bb8d2e77d98 to your computer and use it in GitHub Desktop.
Save Jeckerson/46f0dfac8b6333fc9b8e9bb8d2e77d98 to your computer and use it in GitHub Desktop.
Benchmark function usage inside for loop

Results

Run # Benchmark 1 (sec) BenchMark 2 (sec)
1 0.2886860370636 0.16710495948792
2 0.31771802902222 0.16766691207886
3 0.27882695198059 0.17383599281311
4 0.2907509803772 0.17733597755432
5 0.28123903274536 0.17464399337769

Conclustion

Inside loop, function called each iteration, which cause almost x2 degradation of performance.

<?php
$start = microtime(true);
$string = 'abcdefghijklmnopqrstuvwxyz';
for ($i = 0; $i < 1000000; $i++) {
for ($a = 0; $a < strlen($string); $a++) {
}
}
$end = microtime(true);
echo $end - $start . PHP_EOL;
<?php
$start = microtime(true);
$string = 'abcdefghijklmnopqrstuvwxyz';
for ($i = 0; $i < 1000000; $i++) {
$strlen = strlen($string);
for ($a = 0; $a < $strlen; $a++) {
}
}
$end = microtime(true);
echo $end - $start . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment