Fluent APIs are 1% faster

Using fluent APIs without a guilty conscience

Fluent APIs are pretty common these days and make our lifes so much easier and the code far better to read. Even the JDK came up with some first fluent APIs many years ago, and we all are used to them meanwhile, like e. g. the well-known StringBuilder API.

Today I came up with the crazy idea to measure whether it will have any impact on performance when using a Fluent API instead of a non-fluent one. So I hacked together a short benchmark using Oracle Java Microbenchmarking Harness and gave it a shot.

The result is that actually Fluent APIs run about 1% faster than non-fluent APIs. Also the binary code is a bit smaller, hence less bytes have to be transferred, stored, loaded, etc. This might not sound dramatic, but hey, you not only get it for free, you even get it at the “cost” of better readability and short code.

Certainly my benchmark is anything but flawless, and the conclusion is not really statistically firm, as I measured more code than just the change from non-fluent to fluent API, and as the statistical error is about the same size of the measured difference. But hey, does anybody really conclude from that flaws that this means that using Fluent API (hence sparing code) would not have any postive effect? ;-)

If my target would be massive performance improvements, certainly this will not be the #1 item to fix. For me the conclusion is that if there is a Fluent API, I will simply use it by default, unless some really good reasons conflict with that, as it makes the source better to read, the byte code shorter, and has no negative side effects – and does not make the program slower.

Fluent API Benchmark Setup

Non-Fluent API

public class MyBenchmark {
  @Benchmark public void testMethod() {
    StringBuilder sb = new StringBuilder();
    sb.append("a");
    sb.append("b");
    sb.append("c");
  }
}

The appending part look like this in byte code:

aload_1
ldc #4
invokevirtual #5
pope
aload_1
ldc #6
invokevirtual #5
pop
aload_1
ldc #7
invokevirtual #5
pop

The class file has a size of 652 Bytes.

JMH says the benchmark measured 38,250,987.105 operations per second.

Fluent API

public class MyBenchmark {
  @Benchmark public void testMethod() {
    StringBuilder sb = new StringBuilder();
    sb.append("a").append("b").append("c");
  }
}

The interesting section is consideraly shorter now in byte code as no more aload_1 and pop are found for the subsequent (fluent) invocations:

aload_1
ldc #4
invokevirtual #5
ldc #6
invokevirtual #5
ldc #7
invokevirtual #5

The class file has a size of 640 Bytes, which is 12 Bytes (1.84%) shorter.

JMH says this version yields 378,78,930.655 operations per second, which is 372,056.450 ops/s faster (0,973%).

Posted in Java, Programming | Tagged , | Leave a comment

Summer Holidays At CERN

My wife and me decided to spend our summer holidays this year at CERN. I’m torn between out-freakingly jumping around in our suite and breaking down crying for  joy!

Aside | Posted on by | Tagged , , ,

My first PGJDBC contribution

Yay! My first PGJDBC contribution got accepted. Hooray! ;-)

Aside | Posted on by | Tagged , , ,

Filed my slides for JavaForumStuttgart

Filed my slides for My talk on JAX-RS 2.1 on JSF2015 web site at JavaForumStuttgart 2015. Just in time. ;-)

Aside | Posted on by | Tagged ,

Reactive Programming with AWT / Swing

Reactive programming is rather popular these days, as it makes it pretty simple to express complex event flows – much better than using lots of manual programming with threads, listeners and concurrency APIs. Also, it combines the conciseness of fluent programming style with the power of modern multi-core CPUs. Even when not using a special library like RxJava, you can just use Java 8’s CompletableFuture to get started with reactive programming.

But what if you need to use AWT / Swing APIs with their special threading conditions?

Don’t panic, the solution is pretty simple, and rather straightforward. CompletableFuture allows you to specify an Executor that will do all the work in the end. And as Executor is just an interface, you can implement it any way you like – even using AWT / Swing APIs. Unless specified, a default thread pool will be used by CompletableFuture, but this is not what we want. We need an AWT / Swing Executor. But where to get it from? Well, Executor is a functional API, so thanks to Java 8’s method handles, things are pretty simple…:

static final Executor AWT = runnable -> {
  if (EventQueue.isDispatchThread())
    runnable.run();
  else
    EventQueue.invokeLater(runnable);
};

CompletableFuture.supplyAsync(..., AWT)...

Ain’t that neat? The same will certainly work for Swing API:

static final Executor SWING = runnable -> {
  if (SwingUtilities.isEventDispatchThread())
    runnable.run();
  else
    SwingUtilities.invokeLater(runnable);
};

CompletableFuture.supplyAsync(..., SWING)...

This proofs that it makes pretty much sense to use modern APIs even with old technology – and might help maintain existing applications a bit longer by partial code reduction using new Java 8 code constructs.

An example might be getting rid of that complex SwingWorker class, as the following does the same for most use cases, but is simpler to read and write:

CompletableFuture.supplyAsync(...).thenAcceptAsync(..., SWING);
Posted in Java, Programming | Tagged , ,

What JAX-RS Filters Are Good For

JUG CH Swiss Army KnifeI recently was asked what JAX-RS Filters are good for. Here’s is the answer: They are simply as versatile as a Swiss Army Knife.

Thanks to JUG CH for this really cool gadget!

Image | Posted on by | Tagged , ,

Thank You, JUG Switzerland!

Swiss FlagJust back from Switzerland where I lectured on “JAX-RS Done Right” at PH Zurich. The room was really jam-packed, and we had to forcefully cut the Q&A to not miss the fun at the after-event and subsequent open-air dinner! Those guys really followed the talk closely and wanted facts, and I really love that with an audience — just like the really relaxed time with the organizers at the beer garden!

Audience at JUG ZurichZurich is really a wonderful town and I loved to stroll the medieval historic centre with my wife who accompanied me to Switzerland and kindly provided graphic spice for me slides. If you ever have a chance for a visit, you should really take a stop there, it’s definitively worth a detour!

Markus Karg standing at Lake Zurich

I’d like to say “Thank You!” once more to JUG CH and particularly to Lukas Eder for the invitation and his kind support. I feel like it wasn’t the last time we met at JUG CH…

P.S.: Thanks for the army knife! I always wanted to have one since I was young!

Posted in Java, Lectures, Programming | Tagged , ,