Reputation: 1438
I'm performance-tuning some Java code that needs to construct a few thousand objects in a hurry. There are some obvious things I've looked at, like making sure the objects are appropriately simple and the constructor is lean and mean. And I'm also looking at options for doing without some of the objects, etc.
Are there specific things I can look at to make the constructor itself take less time? Is there another way to get the right number of objects in place without calling the constructor perhaps, maybe using clone()
or some other runtime API instead? Or are there hints I could give the VM or compiler, perhaps, to help streamline this part of the program?
Upvotes: 4
Views: 1400
Reputation: 10020
The best way is to avoid object creation as much as possible. Not only does object creation have its cost, but so does cleaning them up afterwards by the garbage collector.
Some ideas would be: try to squeeze your data into primitive types instead, replace simple struct-like objects with preallocated parallel arrays of simple types, make your objects mutable, and reset them and re-use them once they are no longer needed (using pooling or ad-hoc), use Javolution to place struct-like data in pre-allocated ByteBuffers/arrays. If you must create new objects, avoid Java collections - they have a lot of overhead (both in memory usage and in object allocation), try arrays or Trove instead.
Perhaps you can also simplify your logic so that you do not need so many objects in the first place.
In any case, run profiling so that you know you are optimizing that which really is your bottleneck. Often, the performance hot spots are at different places than intuition tells.
Upvotes: 1
Reputation: 21359
Can you go parallel, or does the thread spinup/sync back into your management system take longer than the creation overhead you're trying to minimise?
Upvotes: 0
Reputation: 2336
Try doing lazy initialization for setup of object state that may not be required immediately.
Upvotes: 0
Reputation: 992857
One of the techniques to speed up object creation overhead in Java is to create a pool of (empty) objects prior to the performance-critical code. Then, in your critical code, you can use the already-constructed objects instead of having to create new ones.
You will, of course, have to manage the use of this pool of objects yourself (to remember which ones are in use and which ones aren't). Depending on your specific application, this may be trivial or more complex.
Upvotes: 0
Reputation: 284786
You can look at the flyweight pattern to share some data between objects.
Upvotes: 0