I have read How do I time a method's execution in Java? and understand the usual possibilities for timing the execution of a method (start/stop timer around execution, use aspects etc.).
I was wondering if Java 8's new method references and lambdas bring any help in reaching the following.
Normal code:
String r;
r = methodCall("foo","bar");
During performance tuning, modify code to something like this, to measure the time spent executing the method
String r;
time(() -> {
r = methodCall("foo", "bar"); // doesn't work as r needs to be effectively final
});
I see that I could do
String r;
r = time1(() ->
methodCall("foo", "bar)
);
(notice the missing semi-colon at the end), using a time1 method like
public static <R> R time1(Supplier<R> s){
long start = System.currentTimeMillis();
R result = s.get();
System.out.println("Execution took " + (System.currentTimeMillis() - start));
return result;
}
or I could do
r = time2(this::methodCall, "foo", "bar");
with a time2 method like
public static <A,B,R> R time2(BiFunction<A, B, R> f, A first, B second){
long start = System.currentTimeMillis();
R result = f.apply(first, second);
System.out.println("Execution took " + (System.currentTimeMillis() - start));
return result;
}
Without return value, I can do much better
time3(() -> {
System.out.println("hello");
});
(notice, semicolon is present) with time3 like this
public static void time3(Runnable r){
long start = System.currentTimeMillis();
r.run();
System.out.println("Execution took " + (System.currentTimeMillis() - start));
}
Is there a better solution when I have a return value?
Do I need closures to be able to do that?