Hacker News new | ask | show | jobs
by pjbringer 4662 days ago
You have to give credit to languages like java or C# which provide the programming interface wich does the right thing. Those who use lower level languages because they want better performance should reconsider unless they have the required know-how. It baffles me that someone would write C++, and mindlessly concatenate string.
2 comments

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.

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();
Except that C++ already has the interface with "the right thing", the author of the post was just unaware of it.

It is a very complex language, and that is definitely a mark against it, but the exact same thing could happen in Java or C# if people didn't know to use StringBuilder instead of relying on concatenating strings.

It's a complex language, but the standard library is tiny compared to e.g. Java's. Anyone programming C++ should at the very least know [io]stringstream.