Compare implementations of a method in Java

This post is history. Read the latest version.

 

Often at work, I look at the code from the legacy of my project and wonder: was this coded this way for a purpose? Is it optimization? And doubt is upon me. My way seems better, but what if it is not? Well, let us just have a quick comparison!

In this article, I will give you the comparison class I created for myself. Quite simple, focused on time (not the best indicator, maybe, but a clue nonetheless). You just have to supply two methods, configure how you want to run it, and run it. Interested?

Basically, I just coded one class. It will execute two methods, compare their results using equals and then performs several timed executions to see which way is faster.

This implies of course that your returned values must have a meaningful implementations of equals.

This is fast-coded and probably not very clean, but it does the job. I use Apache’s commons-lang for its StopWatch (noticed some problems when using System.currentTimeMillis(), though I cannot explain why. See POM lower for dependency declaration.

You can determine how many execution are performed per time-check with ITERATIONS. Also, to avoid any processing-cache-related problems, I tend to execute several time-checks and discard the first one if results seem astray. TIME_CHECKS sets the number of time-checks executed.

Then, of course, do not forget to set method1 and method2.

Here is my code (I wanted to test if the sense of a comparison had an impact, as I was once advised to use the lower than test rather than the greater than test each time I had the choice):

The POM:

And an example of output:

Published by

Cyrille Chopelet

Programming addict, UX philosopher, casual gamer, sci-fi enthusiast, hi-tech dilettante, ... Some people even call me a geek.

One thought on “Compare implementations of a method in Java”

Comments are closed.