Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java call type performance

I put together a microbenchmark that seemed to show that the following types of calls took roughly the same amount of time across many iterations after warmup.

static.method(arg);
static.finalAnonInnerClassInstance.apply(arg);
static.modifiedNonFinalAnonInnerClassInstance.apply(arg);

Has anyone found evidence that these different types of calls in the aggregate will have different performance characteristics? My findings are they don't, but I found that a little surprising (especially knowing the bytecode is quite different for at least the static call) so I want to find if others have any evidence either way.

If they indeed had the same exact performance, then that would mean there was no penalty to having that level of indirection in the modified non final case.

I know standard optimization advice would be: "write your code and profile" but I'm writing a framework code generation kind of thing so there is no specific code to profile, and the choice between static and non final is fairly important for both flexibility and possibly performance. I am using framework code in the microbenchmark which I why I can't include it here.

My test was run on Windows JDK 1.7.0_06.

like image 348
mentics Avatar asked Nov 13 '22 17:11

mentics


1 Answers

If you benchmark it in a tight loop, JVM would cache the instance, so there's no apparent difference.

If the code is executed in a real application,

  1. if it's expected to be executed back-to-back very quickly, for example, String.length() used in for(int i=0; i<str.length(); i++){ short_code; }, JVM will optimize it, no worries.

  2. if it's executed frequently enough, that the instance is mostly likely in CPU's L1 cache, the extra load of the instance is very fast; no worries.

  3. otherwise, there is a non trivial overhead; but it's executed so infrequently, the overhead is almost impossible to detect among the overall cost of the application. no worries.

like image 56
irreputable Avatar answered Dec 18 '22 00:12

irreputable