r/learnjava • • Jan 12 '21

Java Interview Questions and Answers

Came across this while preparing myself, you can refer to this if you are preparing for Java interview. Hope you find this useful. :)

68 Upvotes

17 comments sorted by

View all comments

Show parent comments

1

u/Kombatnt Jan 13 '21

I apologize, I wasn't trying to provoke anyone. You're right, I neglected to consider the situation where a String is being built up in a loop. I'm not denying that a StringBuilder would be faster than String concatenation in that situation - I'm simply saying that (at least in my opinion), it doesn't matter. String concatenation is more readable, so that's the approach I would prefer.

In my experience, and in virtually all literature I've read, performance concerns take a distant back seat to readability and maintainability. I merely meant to push back a little against the dogmatic pursuit of squeezing every last nanosecond of performance out of an otherwise simple construct.

3

u/nutrecht Jan 13 '21

It's not a matter of 'squeezing out nanoseconds' and you're completely misunderstanding the premature optimization quote.

It's really about the amount of objects being created. A lot of intermediate objects mean the GC has to clean them all up again. These kinds of transformations are quite common, and a list of 1000 elements can easily result in a single call having a thousand or even multitudes of that being created for noting, when a single StringBuilder would suffice.

This is NOT a premature optimization!

1

u/Kombatnt Jan 13 '21

You piqued my curiosity, so I just wrote a quite little test program to compare just how much of a gain we're actually taking about here. When looping 1,000 times, String concatenation took 2 milliseconds, while the StringBuilder approach was less than a millisecond. Repeating it with 10,000 iterations, the String concatenation approach took 134 milliseconds, while the StringBuilder was still less than 1.

So the difference in performance is admittedly considerable. My question is, "do I care if the loop takes 2 milliseconds or 0? Is it worth the additional syntactic complexity?" My answer to both is "No."

I think ultimately, this is really all we're disagreeing on. I'd still take the string concatenation approach, because I don't care about 2 milliseconds vs. 0. I'd still look for ways to rewrite it more concisely (such as my stream suggestion above). But for very large datasets, if the delay were to actually become noticeable, then the StringBuilder offers a considerable performance improvement.

Cheers.