Faster than a constructor?

I am setting up some Java code that must quickly construct several thousand objects. There are some obvious things that I looked at, for example, to make sure the objects are simple enough and the constructor is lean and average. And I am also considering options without any objects, etc.

Are there any specific things that I can look at to make the constructor itself less time? Is there any other way to get the correct number of objects in place without calling the constructor, perhaps using clone() instead or some other runtime API? Or are there tips that I could give the VM or the compiler, perhaps to simplify this part of the program?

+4
source share
5 answers

The best way is to avoid creating objects as much as possible. Not only does the creation of an object have its costs, but it also cleans them after garbage collection.

Some ideas: try to compress your data into primitive types instead, replace simple structural objects with pre-allocated parallel arrays of simple types, make your objects mutable and reset them and reuse them as soon as they are no longer needed (using a pool or ad- hoc), use Javolution to place structured data in pre-allocated bytes / arrays. If you must create new objects, avoid Java collections - they have a lot of overhead (both in memory usage and in allocating objects), try using arrays or Trove.

Perhaps you can also simplify your logic so that you don't need so many objects in the first place.

In any case, do the profiling so that you know that you are optimizing what really is your bottleneck. Often, performance hotspots are in different places than intuition says.

+1
source

You can look at the flyweight template to share some data between objects.

0
source

One way to speed up the overhead of creating objects in Java is to create a pool of (empty) objects up to performance-critical code. Then in your critical code, you can use already built objects instead of creating new ones.

Of course, you must manage this pool of objects yourself (remember which of them are used and which are not). Depending on your particular application, this may be trivial or more complex.

0
source

Try lazy initialization to set the state of an object, which may not be needed immediately.

0
source

Can you go in parallel, or resume / synchronize the flow in your control system, will take longer than the creation overhead that you are trying to minimize?

0
source

Source: https://habr.com/ru/post/1398698/


All Articles