Quantcast
Viewing all articles
Browse latest Browse all 15

Answer by mikera for Should we avoid object creation in Java?

Other posters have rightly pointed out that object creation is extremely fast in Java, and that you should not usually worry about it in any normal Java application.

There are a couple of very special situations where is is a good idea to avoid object creation.

  • When you are writing a latency-sensitive application and wish to avoid GC pauses. The more objects you produce, the more GC happens and the greater the chance of pauses. This might be a valid consideration for relevant for games, some media applications, robotic control, high-frequency trading etc. The solution is to pre-allocate all the objects / arrays you need up front and re-use them. There are libraries that specialise in providing this kind of capability, e.g Javolution. But arguably, if you really care about low latency you should be using C/C++/assembler rather than Java or C# :-)
  • Avoiding boxed primitives (Double, Integer etc.) can be a very beneficial micro-optimisation in certain circumstances. Since unboxed primitives (double, int etc.) avoid the per-object overhead, they are much faster CPU intensive work like numerical processing etc. Typically, primitive arrays perform very well in Java so you want to use these for your number crunching rather than any other kinds of objects.
  • In constrained memory situations you want to minimise the number of (active) objects created since each objects carries a small overhead (typically 8-16 bytes depending on JVM implementation). In such circumstances you should prefer a small number of large objects or arrays to store your data rather than a large number of small objects.

Viewing all articles
Browse latest Browse all 15

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>