wasteofserver / site-comments

wasteofserver.com comments are hosted here
0 stars 0 forks source link

premature-optimization-where-software-thrives-unless-you-kill-it-first-a-tale-of-java-gc/ #8

Open utterances-bot opened 6 months ago

utterances-bot commented 6 months ago

Premature optimization, where software thrives unless you kill it first - a tale of Java GC

Will a LinkedList be faster? Should I swap the for each with an iterator? Should this ArrayList be an Array? This article came to be in response to an optimization so malevolent it has permanently etched itself into my memory.

https://wasteofserver.com/premature-optimization-where-software-thrives-unless-you-kill-it-first-a-tale-of-java-gc/

FlorianSchaetz commented 6 months ago

Your visitedCountries has a design flaw: You are exposing an internal, MUTABLE ArrayList to the outside. Since anyone calling your method may ADD things to this list, the next caller may get a list filled with random countries, even as the class thinks that noCountryVisitedYet. While I am not extremely happy with how immutable lists are defined in the JDK, at least returning Collections.emptyList(); would give you the assurance that nobody can pollute your state - at the cost of unexpected exceptions for the caller, when they try to work with the returned list.

As for the StringBuilder example, this might be a fine example for premature optimization, since it is entirely possible that the compiler already translates this into a StringBuilder. it is clever like this.

And there is a lot(!) more to say about different garbage collectors, their use-cases, drawbacks and configuration options. Basically its a science in itself, albeit one that at least 90% of the developers do not have to worry about, because the default is quite ok.

frankielc commented 6 months ago

@FlorianSchaetz thank you for your time and detailed explanation! It means a lot. I've fixed the error and edited the article with a thank-you note linking to your site. If for any reason you don't want it, please message me.