← Back to context

Comment by JohnMakin

12 days ago

When I was still a student I worked mostly with Java and had to solve a simple word frequency problem for a series of assignments. The first several assignments everything worked as expected, and then one case in the test suite kept crashing the JVM or freezing it entirely.

It was then that I learned that String is immutable in Java and that when I tried to ingest a novel into a string one token at a time like str += token; I was destroying/recreating the entire string each time, which was fine during the small cases, but had a hidden exponential effect.

It was then I learned about StringBuilder and laughed that such a seemingly innocent line would contain such a large footgun. As a student, I had absolutely no way of learning about language semantics like that except through that mistake.

> had a hidden exponential effect

Quadratic, I believe. You create a sequence of strings of length 1, 2, 3, ..., n, which is about n^2/2. Of course it isn't that simple (memory alignment and all that), but it doesn't look exponential.

  • Good point but this is actually a very interesting problem that has me digging through the implementation of String again

I also made this mistake once upon a time.

I like this since it's such a good example of how bad API design can mislead the developer and lead to subtle mistakes with substantial consequences. It is right for the JVM to have special handling for strings due to their ubiquity and unique characteristics, but it should be reflected in the API design to avoid encouraging horrible mistakes like that.