3

I'm having some trouble with a game developed in Java which is kinda slow. I benchmarked it a little bit and found the problem: most of the time, the JVM is in the Object.<init>() since there are a lot of objects which gets created and destroyed every tick.

This class which gets created this often is a really small class, just 3 integers, nothing more. But this was a problem I tried to solve. So I started a few tests on how I could increase the speed. What I found is unexpected. First off, code I tested with is as follwos:

public class NewVsCloneTest implements Cloneable {
    int a = 0;
    int b = 0;
    int c = 0;

    public static void main(String... args) throws Exception {
        Stack h = new Stack();
        System.out.println("Benchmarking Copy vs Clone...");
        long time = 0;
        long n = 0, c = 0, s = 0;
        NewVsCloneTest obj = null;
        for(int num = 0; num < 50; num++){
            time = System.currentTimeMillis();
            for(int i = 0; i < 10000000; i++){
                obj = new NewVsCloneTest();
            }
            n += (System.currentTimeMillis() - time);
            System.out.println("New took " + (System.currentTimeMillis() - time) + " MilliSeconds");
            time = System.currentTimeMillis();
            for(int i = 0; i < 10000000; i++){
                obj = (NewVsCloneTest) obj.clone();
            }
            c += (System.currentTimeMillis() - time);
            System.out.println("Clo took " + (System.currentTimeMillis() - time) + " MilliSeconds");
            time = System.currentTimeMillis();
            for(int i = 0; i < 10000000; i++){
                obj = h.getOne();
                h.pushOne(obj);
            }
            s += (System.currentTimeMillis() - time);
            System.out.println("Sta took " + (System.currentTimeMillis() - time) + " MilliSeconds");
        }

        System.out.println("After 50 runs, new took " + n + ", clone took " + c + " and stack took " + s);
        System.out.println("On average, new took " + n / 50.0 + ", clone took " + c / 50.0 + " and stack took " + s / 50.0 + " per 10 mio runs.");
    }

    public static class Stack {
        private NewVsCloneTest[] vars = new NewVsCloneTest[10];
        {
            for(int i = 0; i < 10; i++)
                vars[i] = new NewVsCloneTest();
        }
        int pos = 9;
        public NewVsCloneTest getOne(){
            return vars[pos--];
        }

        public void pushOne(NewVsCloneTest var){
            vars[++pos] = var;
        }

    }

}

The results I get:

After 50 runs, new took 3462, clone took 5784 and stack took 4132
On average, new took 69.24, clone took 115.68 and stack took 82.64 per 10 mio runs.

So, this was really unexpected for me, that new is faster than the small stack-implementation. I mean, the stack already can do nothing but get and put one. No rangechecks, no size-change, just nothing. I even gave "NewVsCloneTests" a few more ints, a few longs, a few objects (just nullptr's) and a few chars, but got the same outcome.

So the thing is, I've seen a lot of source code where one cached instances of classes which will get needed very often but just for a short time, so I thought it would make a difference. But my results show me that even worse.

How can I handle this particular problem?

The class which gets instantiated this often is just a dataholder for coordinates (x, y, z), and it gets instantiated this often (copy-constructed if you will) because I can't hand out my originals.

  • 1
    Instances of NewVsCloneTest can be initialized with statically-known data, and that data happens to be the default value for all the fields. That probably makes a difference. The JVM might also be optimizing the instantiations away since you don't actually do anything with them, while the Stack code has to decrement and increment a variable and the array code has to check the index and that the class of object can be stored in that kind of array. Try adding an operation like incrementing a, b or c and see if the relative speeds. – Doval Dec 24 '14 at 12:19
  • Unrelated to this question but related to the problem you're trying to solve, pooling objects may have worse performance if the memory where the pool resides gets evicted from the CPU cache. You might get a cache miss accessing the object pool, and you might get a second miss accessing the object itself. I imagine the heap area where new objects are allocated is generally hot in the cache and the JVM can use the stack instead in certain cases. You should definitely benchmark both approaches in your actual application and see which one fares better. – Doval Dec 24 '14 at 12:33
  • 3
    Searching about your topic I have found this interesting answer (I would say related, not duplicated): programmers.stackexchange.com/a/149569 – Tobías Dec 24 '14 at 12:58
  • Obviously jvm people saw the problem that you're having and got there first. – imel96 Mar 20 '15 at 0:09
3

Pass the x, y, z around as primitives (i.e. int or long or whatever). Since they are primitives, they are passed by value. Hence there is no need to copy an object when passing them to another piece of code, they're copied as part of the pass-by-value operation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.