Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Costs of operations in Java

Tags:

java

Is there a why to tell, how expensive an operation for the processor in millisecons or flops is? I would be intrested in "instanceof", casts (I heard they are very "expensive").

Are there some studies about that?

like image 674
Stefan Avatar asked May 12 '11 07:05

Stefan


2 Answers

It will depend on which JVM you're using, and the cost of many operations can vary even within the same JVM, depending on the exact situation and how much optimization the JIT has performed.

For example, a virtual method call can still be inlined by the Hotspot JIT - so long as it hasn't been overridden by anything else. In some cases with the server JIT it can still be inlined with a quick type test, for up to a couple of types.

Basically, JITs are complex enough that there's unlikely to be a meaningful general purpose answer to the question. You should benchmark your own specific situation in as real-world a way as possible. You should usually write code with primary goals of simplicit and readability - but measure the performance regularly.

like image 58
Jon Skeet Avatar answered Sep 26 '22 00:09

Jon Skeet


The time where counting instructions or cycles could give you a good idea about the performance of some code are long gone, thanks to many, many optimizations happening on all levels of software execution.

This is especially true for VM-based languages, where the JVM can simply skip some steps because it knows that it's not necessary.

For example, I've read some time ago in an article (I'll try to find and link it eventually) that these two methods are pretty much equivalent in cost (on the HotSpot JVM, that is):

public void frobnicate1(Object o) {
  if (!(foo instanceof SomeClass)) {
    throw new IllegalArgumentException("Oh Noes!");
  }
  frobnicateSomeClass((SomeClass) o);
}

public void frobnicate2(Object o) {
  frobnicateSomeClass((SomeClass) o);
}

Obviously the first method does more work, but the JVM knows that the type of o has already been checked in the if and can actually skip the type-check on the cast later on and make it a no-op.

This and many other optimizations make counting "flops" or cycles pretty much useless.

Generally speaking an instanceof check is relatively cheap. On the HotSpot JVM it boils down to a numeric check of the type id in the object header.

This classic article describes why you should "Write Dumb Code".

There's also an article from 2002 that describes how instanceof is optimized in the HotSpot JVM.

like image 28
Joachim Sauer Avatar answered Sep 22 '22 00:09

Joachim Sauer