Question: If we add more comments, does the program takes more time to execute? Why?
No. Comments have no effect on execution.
They will slow the compiler down a tiny bit - but even that should be imperceptible unless you have a ridiculous number of comments.
The "effect" you're noticing is more to do with the way you're timing things - using System.currentTimeMillis
for benchmarking is a bad idea; you should use System.nanos
instead as it typically uses a higher-accuracy clock (suitable only for timing, not for determining the "wall clock" time). Additionally, typically benchmark programs should run their "target" code for long enough to warm up the JIT compiler etc before actually measuring. Then you need to consider other things which might have been running on your system at the same time. Basically there's a lot involved in writing a good benchmark. I suggest you look at Caliper if you're going to be writing any significant benchmarks in the future.
You can verify that there's no difference just due to the comments though - compile your code and then run
javap -c Stopwatch
and you can look at the bytecode. You'll see there's no difference between the different versions.