In a Java REST service performance test, I got an unexpected pattern: a method that creates and returns always the same value object in each invocation runs faster than another version that just returns the value object stored in a class or object field.
Code:
@POST @Path("inline") public Response inline(String s) {
return Response.status(Status.CREATED).build();
}
private static final Response RESP = Response.status(Status.CREATED).build();
@POST @Path("staticfield") public Response static(String s) {
return RESP;
}
private final Response resp = Response.status(Status.CREATED).build();
@POST @Path("field") public Response field(String s) {
return resp;
}
Byte code:
- Inline (faster): getstatic, invokestatic, invokevirtual, areturn
- Static filed (slower): getstatic, areturn
- Object field (slower): aload, getfield, areturn
Performance (using Apache AB, single thread, several runs with consistent results):
- Inline: 17078.29 [#/sec] (mean)
- Static field: 5242.64 [#/sec] (mean)
- Object field: 5417.40 [#/sec] (mean)
Environment: RHEL6 + JDK Oracle 1.7.0_60-b19 64bits
Is is possible that the JVM optimized the inline version with native code, but never considered optimizing the other two because they are already pretty small?