Tag Archives: Java

Why clone is faster than constructor copy

This post is a followup on my previous post about copying objects in Java. After I published that post I got a question from Sven Reimers (@SvenNB) why there is a big performance different between clone and copying via constructor. In this post I will try to answer this question.

Code in question

Just to recap what we are looking at. There are 2 classes implementing copy() method:

  • Copy via clone():
  • Copy via constructor:
  • Both of these classes inherit from the common base class that defines state to be copied:

Clone under the hood

java.lang.Object defines clone() method as native thus giving JVM possibility to use intrinsics. And in fact this is what OpenJDK JVM implementation is doing under the hood:

Unfortunately I was not able to find exactly how such intrinsified clone() method call would look like. If any of you knows the answer I would be more than happy to hear about it!

Test code and results

This time I won’t be using JMH running my tests, because I just need to force JVM to compile methods in question. For each case there is a dedicated test class (i.e. TestClone.java and TestConstructor.java) that invokes copy() method 500 000 times during warmup phase and then another 10 000 000 during actual test phase. These numbers are not particularly relevant and they were chosen to ensure that JVM will compile copy methods into native code.
I will use 1.7.0_45 JDK version.

Here are test classes:

I ran both tests with -XX:+PrintCompilation option and got the following results:

  • Clone:
  • Constructor:

This by itself is not telling us much except that in the second (constructor) case there are 2 more entries that were compiled (i.e. BaseClass::<init> and Root::<init>).

The real fun is to look into generated assembler code (i.e. -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly). If you want to know how to dump assembly you can use java-print-assembly instructions provided by Nitsan Wakart on his blog. Links to proper binaries saved me tons of time today. 😉

I will show here only relevant part of the assembly dumps which contain only compiled callCopy() method from each test class, because it is the one we are interested in:

As you can see clone case has much shorter assembler code and basically it is just an *invokespecial clone invocation. Whereas in the constructor case we see much bigger assembler output and in essence it contains multiple *putfield invocations.

CPU counters

Eventually I managed to compile Intel Performance Counter Monitor 2.5.1 on my OS X 10.9.
Here are the results of running clone and constructor code under PCM (NB: I changed number of iterations to 20'000'000 in test() method for this run):

  • Clone:
  • Constructor:

What this output shows is that clone case is faster because amount of instructions executed is lower, i.e. there is less code to execute:

  • TestClone:

    Instructions retired: 10 G ; Active cycles: 16 G ; Time (TSC): 3425 Mticks

  • TestConstructor:

    Instructions retired: 11 G ; Active cycles: 17 G ; Time (TSC): 3988 Mticks


Devoxx 2012 trip report

Here it was another amazing Devoxx conference. Tons of new stuff to learn and a lot of new and familiar faces to discover.

As already became a tradition each year of Devoxx brings some innovation and this year wasn’t exceptional. The big theme of this year was NFC, it was used in the wristbands that each attendee had to wear. With such chips it was possible to get food but also to vote for talks after they complete. This was done via amazing piece of machinery (picture) that had and NFC reader and was sending HTTP POST to a server running and a Raspberry Pi device. The server was putting votes to the MongoDB and cost of the server is only 35 EUR (i.e. cost of Raspberry Pi itself)! It was so COOL!!!

It always pays off to go to Devoxx for full 5 days as during first 2 University days one can get a lot more deeper insights and have more access to the presenters. This year was not different in this respect as one could attend some sessions that were not repeated during conference. For example “Performance optimization methodology” (Performance Methodology part 1/2 and Performance Methodology part 2/2) by Kirk Pepperdine (@kcpeppe) and Alexei Shipilev (@shipilev) which was simply brilliant. If you want to learn more on the subject of performance tuning and how to find performance problems watch videos on Parleys.

Conference itself started on Wednesday and as already became a tradition opening keynote by Stephan Janssen had some surprises.
For one thing he showed video from the first Devoxx4Kids an event for kids from 10 to 14 years old which were hacking some robots and learning some programming. If you watch video you’ll see how happy were those kids. Later during JUG’s BOF it was agreed that JUG leaders will do such events in their cities. Which I think is a great way to bring more young boys and girls into programming.

Second announcement was about Devoxx UK an event which will take place in March 26-27, 2013 and will be organized by London JUG. The idea is to bring Devoxx experience to UK and also leverage great Java community of London (they have 3000 JUG members and are very active in the JCP and OpenJDK realms). Devoxx UK will be followed by Devoxx France (28.03-30.03) and thus speakers and attendees will have possibility to enjoy a week of Devoxx in 2 different countries and cultures! Just hop on EuroStar train and in 2 hours you are in Paris! (just bear in mind that Devoxx France is 75% done in French language)

Third announcement was about complete re-write of Parleys in HTML 5. So Flash is gone and now entire web site will leverage latest and greatest technologies. For one thing it will retain all functionality but will add more features. For example there is one full blown editor that allows editing presentation with slides and video. Have you ever tried to edit video clips in HTML, now you can. This version will be available in March 2013 before Devoxx UK. Which is great because with new Parleys they will also change upload rates of recorded videos – videos will be uploaded after sessions directly so one could enjoy conference experience real time! 😉

Next keynote was handed off to Oracle. Aside from corporate mantra about billions of devices running Java etc. there were couple of interesting demos. For one it was JavaFX demo that showed kiosk that was created for JavaOne (picture) and which features were used (re-write this sentence). Next was Joe Darcy talking briefly about upcoming JDK8 with lambdas and new Date-time API (JSR-310) besides that there will be plenty of other features like annotation on types (JSR-308) and repeating annotations (JEP-120). Afterwards we heard about upcoming Java EE 7 and it’s features and also plans for Java EE 8.

After Oracle stage was given to Neal Ford (@neal4d) and his “When Geek Leaks” presentation (video, unfortunately full version available to subscribers only however it would become available for free before Devoxx 2013). As always quality of the presentation was superb. Neal talked about concept of leaking or cross-pollination between different domains and how it can be good and bad. One of the examples was article in Forbes Now Every Company Is A Software Company which basically says that any company that wants to succeed in modern world needs to invest in software (e.g. should have strong mobile and web presence to stay ahead of competition). Neal used it as an example of software geek leaking into other domains and transforming them.

After the keynote the conference itself officially started and went for great 2.5 days. Devoxx did it again – delivered great experience and content. 😉 For the rest please check out videos on Parleys. Most of them are already free and more and more will be made available for free before Devoxx 2013.

P.S. Here is my list of best sessions (without any particular order):


In my previous post on Java 7 I’ve outlined some problems one might face when converting project to use it. Here I would like to outline issues I’ve discovered when I actually migrated code from Java 6 to Java 7.

Contrary to what I’ve been expecting, actual upgrade to Java 7 turned out to be bumpier. One of the reasons was converting code to use new Java 7 features. For that I’ve used NetBeans 7.2 RC1 and it’s “Inspect and transform” feature. (By the way Intellij IDEA also has capability of automatically converting code to Java 7)

Overall the tool did a great job and I was able to convert big project of several thousand classes in a matter of minutes. However since conversion resulted in more than 1000 classes modified it was not feasible to manually check all of them. As the result I’ve found about problems out only after nightly CI build have failed. Which brings me to the core of the post – a multi-catch conversion issues.

Multi-catch conversion pitfalls

So here is existing code from one of the classes before conversion to Java 7:

And here is the result of the conversion:

As you can clearly see the updated code is not semantically equivalent to the original code!!!

Before the change method rollbackTransaction(Throwable) would have been called in case of any exception (checked or unchecked), but after change it is called only in case if IOException or XMLStreamException is thrown.

As the result after such a change you get leaking transactions (zombies that are not closed). And this is kind of a bug that one would call a blocker or if you wish absolute top priority.

To me this conversion issue seems like a bug in NetBeans and a scary one. But it should be also a remainder to all of us to check the results of any automagic stuff that our tools are doing for us. 😉

Updated (2012-07-14):
I’ve submitted bug report to NetBeans team as Bug 215546. Let’s wait for evaluation on this one.

Recursive generics to the rescue

In this post I will show how something as non-intuitive (read ugly) as recursive generics can help to solve problem of creating extendable Builders.

But first we need to define what are we trying to achieve. We need to build set of Builder objects that facilitate creation of non-trivial domain objects and provide fluent interface (for the definition of fluent interface see Martin Fowler’s article) for user along the lines.

So let’s start with defining our 3 builder classes:

  • BaseBuilder
    BaseBuilder class
  • ConstraintBuilder
    ConstraintBuilder class
  • And finally ConcreteBuilder
    ConcreteBuilder class

Now we want to write client code that uses ConcreteBuilder. The code we want to have is the following:
Client code

Notice however that this code has compilation error:

"The method equalTo(int) is undefined for the type BaseBuilder".

Java compiler tells us that we are trying to invoke method on the class BaseBuilder whereas we are assuming to be working with class ConcreteBuilder.

OK, so how do we suppose to fix the code. I know of 2 possible solutions:

  1. Use covariant return types and override methods from base classes
  2. Use recursive generics when defining builder classes

Covariant return types

From wikipedia:

In object-oriented programming, a covariant return type of a method is one that can be replaced by a “narrower” type when the method is overridden in a subclass.

Thus knowing this we can fix our builders by overriding methods from parent classes and forcing them to return instance of the leaf class instead. So here is how our classes end up looking in the end:

  • BaseBuilder (not changed)
    BaseBuilder class
  • ConstraintBuilder
    ConstraintBuilder class
  • ConcreteBuilder
    ConcreteBuilder class

With these changes in place our client code now compiles and runs, but we had to do too much work in my opinion. Notice for instance that we had to override all methods from base classes in each and every derived class.

We are forced to do this whenever subclass adds new methods, cause we need to provide end user with flexibility of invoking methods in any order irrespective of where they are defined.
Also in this example it was not necessary to do this for ConcreteBuilder class but I showed it here for completeness, mainly to stress how much involved first approach is.

Enough for the ugliness, so let’s checkout second approach.

Recursive generics

OK, so is there better way to achieve the same goal without repeating same steps for each builder subclass? The answer is yes.

We can use generics while defining our builders to tell Java that return type of methods is not the builder’s class but rather the subclass of the builder, hence recursive generic definition.

Let’s see what it means for our builders:

  • BaseBuilder
    BaseBuilder class
  • ConstraintBuilder
    ConstraintBuilder class
  • ConcreteBuilder
    ConcreteBuilder class

And the client code haven’t changed at all, it still compiles and runs as before:
Client code

Let’s have a quick recap of what we just did. We changed definition of the BaseBuilder class to contain recursive generic parameter E (i.e. BaseBuilder<E extends BaseBuilder>). This allowed us change return type of the methods from BaseBuilder to E, which effectively tells Java compiler that method returns some subclass of BaseBuilder class.

Then we did the same for ConstraintBuilder class (i.e. ConstraintBuilder<E extends ConstraintBuilder>) which again tells javac that return type is some subclass of ConstraintBuilder class.

And finally we stopped recursion for class ConcreteBuilder by specifying itself as the generic parameter while extending ConstraintBuilder class (i.e. ConcreteBuilder extends ConstraintBuilder<ConcreteBuilder>). Since this class is at the bottom of our inheritance hierarchy we could stop using generic parameter. However if it would have subclasses on it’s own then we would have to repeat declaration similar to that of ConstraintBuilder class.

Notice how much less effort was to implement second solution. Despite of some minor noise such as usage of @SuppressWarnings("unchecked") annotation to eliminate compilation warnings and casts to E this solution is much cleaner, easier to understand and maintain. There is no code duplication that we saw in first solution and it scales well when the inheritance hierarchy is getting bigger and deeper.

To conclude:
Java’s generics can be real pain (especially when wildcards are used), but in some cases clever usage of generics can save your day! 😉

Latency Tip Of The Day

"Nothing is more dangerous than an idea when it is the only one you have." (Emile Chartier)

Psychosomatic, Lobotomy, Saw

"Nothing is more dangerous than an idea when it is the only one you have." (Emile Chartier)

"Nothing is more dangerous than an idea when it is the only one you have." (Emile Chartier)

Mechanical Sympathy

"Nothing is more dangerous than an idea when it is the only one you have." (Emile Chartier)