Hasan's Blog

Elegantly Log Elapsed Time in Java

Avoid repeating your code

) Have you ever needed to compare the performance of two methods? the easiest way is to log the execution time of each method, you probably end up with something like this:

but if you wanted to compare more than two methods the process gets ugly as you end up repeating yourself:

in this article I will explain a better way.

Don’t repeat yourself

it would be better if we can write a method that takes as argument another method and runs that method inside the time logging code (such as the one above), well, it turns out we can write such a method using Java functional interface and method referencing, but what are those things?

Java Functional Interface

A functional interface is an interface that contains one and only one abstract method.

because it has only one method, it means we can implement this interface using a lambda, or we can use method referencing.

Java Method Referencing

As the name suggests, method referencing is the process of passing a reference of a method to be stored in a variable, for the above interface, the type of the variable will be MyFunctional and here is how we do it:

first we create a static method that matches the signature of the abstract method in our interface

and then we put the reference in a variable as follows:

similarly, we can pass a method reference to a method that accepts an argument of type MyFunctional

and we can call the above method as follows:

Putting it all together

what’s left is to add time logging to our logTime method, and it ends up like this:

Small Improvements

The above code uses a functional interface that we created manually, it turns out that Java has built-in functional interfaces that we can use to speed things up,

in this case we will use BiFunction<T,U,R> since it fits myAdd’s signature (it accepts two arguments and returns result), you can look up the list of functional interfaces which fit most common method signatures.

using BiFunction<T,U,R> our code will look like this:

so now, every time we want to log a method that accepts two Integer arguments and returns an Integer result we can simply pass it to the log method above as follows

Extra note

in Python, we would do the same thing except we would use Decorators instead, and since functions are 1st class citizens we would end up with a much more usable scheme.

This project is maintained by hasan-aga