Sunday, 15 July 2007

Accessing JavaBeans Nested Properties: testing Spring, BeanUtils and OGNL

One our application needs to access properties from a javabean using reflection
e.g. get(“property1”, object)…

Rather than re-inventing the wheel, I thought that we should use a library. There are quite a few that do this kind of get/set properties… So the question was: Which One???

I know of:

  1. Spring beans (2.0.5)

  2. Apache Commons BeanUtils (1.7.0)

  3. my colleague Gerald mentioned OGNL from (pronounced ‘like a drunken orthogonal’ to quote their documentation).

So with 3 candidates… which one is the best performing?

OGNL seems to be, by far, the most flexible and rich library, but does that means it runs like a dead dog?

I limited the problem to accessing a property value: being simple, nested or as part of an array.
The Test: I shall access 100,000 a series of 8 properties. The classes are:

public class A {
private int intProperty;
private Long longProperty;
private String stringProperty;
private Date dateProperty;
private B b = new B();
public class B {
private int intProperty = 5;
private C c = new C();
private D[] d = new D[10];
public class C {
private String stringProperty;
public class D {
private int intProperty = 1;

The Test creates one instance of A, that contains 1 instance of B which contains 1 instance of C and an array of 10 Ds. I hope this is clear…
The set of properties to get are: "intProperty", "longProperty", "dateProperty", "stringProperty", "b.intProperty", "b.c.stringProperty", "b.d[1].intProperty", "b.d[7].intProperty".

So… the results?

LibraryTotal time (ms)average per set (micro sec)
Spring1,783 ms17.8 micro sec
Bean Utils2,242 ms22.4 micro sec
OGNL50,293 ms503 micro sec
OGNL Expression1,595 ms16 micro sec

What does this tell us?

OGNL is at the same time the slowest and the fastest library on my laptop (Lenovo, dual-core) under java 1.5.0_10. OGNL has 2 mechanisms, one is simply to call Ognl.getValue(“pathToProperty”, object) and the other one is to evaluate the expression upfront by Object expression = Ognl.parseExpression(“pathToProperty”) and then Ognl.getValue(expression, object);

The second one is the fastest mechanism so, if you have the ability to ‘pre-compile’ your expressions, OGNL is for you… otherwise Spring Beans is doing a good job!

The entire source code and Eclipse project is available here, feel free to comment and tell us about your experience.