Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Java slow when creating Objects?

In my current project (OpenGL Voxel Engine) I have a serious issue when generating models. I have a very object oriented structure, meaning that even single parameters of my vertices are Objects. This way I am creating about 75000 Objects for 750 voxels in about 5 seconds. Is Java really this slow when allocating new Objects or do I miss a big failure somewhere in my code?

like image 567
th3falc0n Avatar asked Jan 10 '14 22:01

th3falc0n


2 Answers

Very big question. Generally speaking, it depends from the object class definition and by the amount of work required to construct object.

Some issue:

  1. avoid finalize method,
  2. tune memory and GC in order to avoid excessive GC activity,
  3. avoid big work during constructor,
  4. do not use syncronization call during object construction,
  5. use Weak references

these issues solved my problem.

See also http://oreilly.com/catalog/javapt/chapter/ch04.html

Finally let me suggest you the (deprecated) Object Pool pattern or reuse objects.

Concluding, no, generally speaking, java object creation is not slow

like image 134
venergiac Avatar answered Oct 28 '22 22:10

venergiac


Of course it isn't. The following code allocates 10 million objects and stores them in an array. On my 5 year old notebook, it completes in 1.4 seconds.

public class Test {
    public static void main(String[] args) {
        Object[] o = new Object[10_000_000];
        long start = System.nanoTime();
        for (int i = 0; i < o.length; i++) {
            o[i] = new Object();
        }
        long end = System.nanoTime();
        System.out.println(Arrays.hashCode(o));
        System.out.println(new BigDecimal(end - start).movePointLeft(9));
    }
}

... and that's even though this benchmark is quite naive in that it doesn't trigger just in time compilation of the code under test before starting the timer.

like image 5
meriton Avatar answered Oct 28 '22 21:10

meriton