Last active
August 12, 2019 21:07
-
-
Save josecanciani/e2e5878d534ad09c357f9d05de2f7882 to your computer and use it in GitHub Desktop.
Performance analysis for exceptions in PHP (1)
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
# All tests running inside a loop of 10 million iterations | |
# lets first try to add some code for reference. Here we are just creating a standard class | |
$ time cat <<EOF | php | |
<?php | |
for (\$i = 0; \$i < 10000000; ++\$i) { | |
\$c = new StdClass(); | |
\$c->var = \$i; | |
rand(\$i, \$i + 1000000); | |
} | |
EOF | |
real 0m1,011s | |
user 0m1,004s | |
sys 0m0,013s | |
# now, let's see if we try catching an exception here | |
$ time cat <<EOF | php | |
<?php | |
for (\$i = 0; \$i < 10000000; ++\$i) { | |
try { | |
\$c = new StdClass(); | |
\$c->var = \$i; | |
rand(\$i, \$i + 1000000); | |
} catch (Exception \$e) { | |
} | |
} | |
EOF | |
real 0m1,072s | |
user 0m1,060s | |
sys 0m0,016s | |
# Surprise! No extra time detected for running inside a try/catch block. | |
# Let's discard PHP is not actually optimizing this by throwing a exception there. | |
$ time cat <<EOF | php | |
<?php | |
for (\$i = 0; \$i < 10000000; ++\$i) { | |
try { | |
\$c = new StdClass(); | |
\$c->var = \$i; | |
if (rand(\$i, \$i + 10000000) === \$i) { | |
throw new Exception('oops'); | |
} | |
} catch (Exception \$e) { | |
echo 'Random exception catched.' . PHP_EOL; | |
} | |
} | |
EOF | |
Random exception catched. | |
real 0m1,099s | |
user 0m1,083s | |
sys 0m0,022s | |
# No significant time added, so adding a catch block does not affect performance. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment