Have you ever asked yourself, “I wonder which of these blocks of code will run
faster?” I know I have and I use a very basic template for setting up these
benchmarking experiments. The gist of the script is to run through each block
of code n times tracking the amount of time and memory it took to run. It’s
not nearly as complete as it could be, but it serves as a good enough starting
point for doing some quick tests.
You can duplicate the test block as many times as you need it. Here’s a working
benchmark I wrote to see if PHP’s built-in array_keys function was actually
faster than doing a foreach:
One improvement would be to track the average time per iteration as well as the
fastest and slowest iteration. I went ahead and threw the code in a
GitHub gist in case anyone wants to fork and improve upon it.