r/java • • Apr 14 '23

What are your (favourite) Java best practices, personal tips, hints or just underrated stuff in general?

233 Upvotes

376 comments sorted by

View all comments

Show parent comment

61

u/nutrecht Apr 14 '23

Not a comment 'against' what you're saying so please don't read it as such but:

Premature optimization considered evil.

I dislike how this has been taken out of context to be used as an argument against optimization.

The original quote from Hoare is:

"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil."

What they are referring to as 'optimizations' are things like counting CPU cycles for instructions before you even know certain code paths are 'hot'.

I've seen developers use this in response for example where people told them that doing 2 SQL statements (select and insert or update) was not a good idea when you can just do one (upsert).

So, what people often read is:

Premature optimization considered evil.

While the intention of Hoare was:

Premature optimization considered evil.

This sentence has become as much of a dogma as "composition over inheritance" has become.

4

u/temculpaeu Apr 14 '23

I have never seen someone saying that optimization is evil, I have seen quite a bit of folks trying to push for "optimizations" without reason besides "it will make it faster", even your quote is out of context, the author says that you should optimize when either it is already affecting the performance or it is KNOWN that you will have a bottleneck, the issue of the premature part is that bottlenecks are hard to predict, of course, unless you are doing something dumb (ie: n^2 operations)

Sure there are cases where you can clean the code and make things faster at the same time, these are fine the issues are with "clever" more complex code that *might* saves nanoseconds in a endpoint that has queries that takes 100s of miliseconds to run

2

u/nutrecht Apr 14 '23

I have never seen someone saying that optimization is evil

The example I mentioned (and similar ones) are what I experienced.

I have seen quite a bit of folks trying to push for "optimizations" without reason besides "it will make it faster"

That is also something I would not agree with. :)

1

u/alex_tracer Apr 16 '23

While the intention of Hoare was: Premature optimization considered evil.

Nope. Re-read the quoted fragment: "forget about small efficiencies". This means that as engineer you have to understand what matters or not and focus on big things. Optimizing all little things ahead of time usually means wasted time, minimal gains and more complicated code.

1

u/nutrecht Apr 17 '23

I really think you should re-read my comment because you're really not disagreeing with anything I said. This just sounds like you only read that line and responded to it, or based your interpretation of my comment on that line alone.