tags:

views:

33

answers:

2
class Test {
    String field
    int num

    public Test (String field, int num) {
        this.field = field
        this.num = num
    }
}

def start = System.currentTimeMillis()

def testObj = new Test("i'm field", 1)

println "Beans: ${System.currentTimeMillis() - start}"

def start2 = System.currentTimeMillis()

def map = [:]
map.field = "i'm field"
map.num = 1

println "Maps: ${System.currentTimeMillis() - start2}"

Output is:

Beans: 3
Maps: 0

My Grails server communicates over JSON. I'm using map <-> JSON conversion but i think it would be better to use beans because in maps case you have to call numerous put() methods...

But simple script shows that Map creating and two put operations are faster than simple object constructor...

So would i continue using maps or beans are preferable ?

+5  A: 

Your script is absolutely meaningless. The operations you are trying to measure are far, far below your measurement threshold. The output is simply random noise. Repeat each assignment a million times and use System.nanoTime(), and then you may get meaningful data.

In any case, if there is a significant difference at all, it is almost certainly not significant for your application. This is a typical example of premature optimization, i.e. a waste of time.

Michael Borgwardt
+2  A: 

Your script proves nothing. It doesn't even do any JSON serialization/deserialization. Even if the microscopic differences between using Maps and Beans is significant to your app, then you've got much bigger problems to worry about that this.

Choose whichever approach is more readable/maintainable/elegant, and forget about performance differences, because they're almost certainly insignificant.

Don