What's add(E e, Object[] elementData, int s) method for?

Wei ding Wong :

I'm reading the source code of ArrayList class and I'm wondering about the method add(E e, Object[] elementData, int s).

I have read its description, but I don't understand some parts of it.

Like these:

keep method bytecode size under 35 (the -XX:MaxInlineSize default value), which helps when add(E) is called in a C1-compiled loop.

  • What is "method bytecode"?
  • Why should it be kept under 35?
  • What is C1-compiled loop?
Joachim Sauer :

The "method bytecode size" is the number of JVM instructions that a method compiles to. Roughly speaking the shorter a method, the lower this number.

The C1-compiler is one of the compiler in the HotSpot VM. Its job is to compile Java bytecode to native code that is actually executed by the JVM.

"Inlining" means putting the code of a method that is called directly into the calling native code instead of actually doing a "jump" instruction. This helps avoid the overhead of the "jump" instruction at the cost of bigger code size.

By default the C1 compiler only inlines sufficiently small methods (measured by method bytecode size).

Extracting that method keeps the bytecode size of the add(E) method below the default threshold for inlining and thus makes it much more likely that add(E) is being inlined (which in turn allows this method to be inlined as well, potentially).

All in all this is a extremely JVM specific optimization that's generally a very bad idea to use in general-purpose code.

The reason this kind of optimization was deemed acceptable here is probably two-fold:

  1. ArrayList.add will be executed a lot in almost all code that runs on Java and
  2. the class itself is shipped with the JVM, so you can always guarantee that it's executed with the JVM that it is being optimized for.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=308768&siteId=1