Hacker News new | ask | show | jobs
by CJefferson 4662 days ago
Code written in Java would have exactly the same problem I believe? You are advised to use a StringBuilder.

C++ has a StringBuilder, it's called std::ostringstream, but the author didn't seem to know about it, so reinvented it.

To be polite, his reinvention is reasonable, and knowing about this problem is useful.

1 comments

Not quite exactly the same issue, not sure about all JVMs but the HotSpot JIT will replace concatenation with StringBuilder usage in many cases but it may not be ideal.

For example it may create a new StringBuilder in every iteration of a loop whereas you may be able to code it such that only a single StringBuilder needs to be created and you may be able to provide better initial array size hinting. If it's just a single concatenation statement, building a log message or something, then using the '+' operator won't have much if any impact on performance.

> Not quite exactly the same issue, not sure about all JVMs but the HotSpot JIT will replace concatenation with StringBuilder usage in many cases but it may not be ideal.

It's not even the JIT, it's a static transformation at byte code creation time. Last I checked:

    String s = "foo" + "bar";
Produced identical byte code to:

    String s = new StringBuilder()
        .append("foo")
        .append("bar")
        .toString();