Quantcast
Channel: Should we avoid object creation in Java? - Software Engineering Stack Exchange
Viewing all articles
Browse latest Browse all 15

Answer by ratchet freak for Should we avoid object creation in Java?

$
0
0

the GC is tuned for many short lived object

that said if you can trivially reduce object allocation you should

one example would be building a string in a loop, the naive way would be

String str = "";while(someCondition){    //...    str+= appendingString;}

which creates a new String object on each += operation (plus a StringBuilder and the new underlying char array)

you can easily rewrite this into:

StringBuilder strB = new StringBuilder();while(someCondition){    //...    strB.append(appendingString);}String str = strB.toString();

this pattern (immutable result and a local mutable intermediate value) can be applied to other things as well

but other than that you should pull up a profiler to find the real bottleneck instead of chasing ghosts


Viewing all articles
Browse latest Browse all 15

Trending Articles



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