Skip to content

Benchmarking PHP: Is it possible to have too many comments?

PHP is an interpreted language; and as such, the computer needs to process the script each time it is run. Honestly, I don’t know much about the internal workings of PHP; so I don’t know how it handles comments in the code. More specifically, I don’t know how well it handles comments.

I have seen sites over the web going back and forth on whether it’s possible to have too many comments. Most I found said that it didn’t really matter; a few said it slowed execution. As I tend to be the type to over comment my code, I decided to test it for myself with some over the top commented code.

So, here we are. If you look at my page on benchmarking PHP, you will see the code I used. Inside the loop was nothing except an echo command to output the position. I looped through 100,000 each with 3 different scripts. The only difference between the three was the amount of comments, and their location.

For all tests, the comment block was around 800 lines of text created by the Word macro =rand(). It was ‘The quick brown fox…” repeated over and over.

Test #1 – No comments
Test 1 was a baseline.

Test #2 – Comments outside loop
Test 2 had the comment block put outside the main loop, so it was only an issue when the file was opened.

Test #3 – Comments inside loop
Test 3 had the comment block moved inside the main loop. Each time the loop was run, the comments would be there.

Results
Please keep in mind that each of these times was for 100,000 loops, so the actual difference in time is much smaller.

The script with no comments took 5.258 seconds to run. Test #2 took 5.291 seconds and test #3 took 5.275 seconds.

Common sense prevailed in that the script with no commenting took the least amount of time to run. However, the difference was almost non-existant; and the amount of commenting was extreme. It’s a 2-4% difference in speed with “The quick brown fox…” repeated for 54 pages. It is doubtful that any script would have this many lines of comments.

It does seem that the third test should have been the slowest of the three, although number two was. Both two and three had to open the same block of comments, but two only had to deal with them once.

In the end, it does appear that commenting can slow execution; but it is such a small difference that it does not negate the benefit of well-commented code.

Published inProgramming

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *