Is Java slow when creating Objects?

th3falc0n picture th3falc0n · Jan 10, 2014 · Viewed 7.7k times · Source

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?

Answer

venergiac picture venergiac · Jan 10, 2014

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