String concatenation vs. interpolation in Ruby

Whenever TIMTOWTDI (there is more than one way to do it), you should look for the pros and cons. Using “string interpolation” (the second) instead of “string concatenation” (the first): Pros: Is less typing Automatically calls to_s for you More idiomatic within the Ruby community Faster to accomplish during runtime Cons: Automatically calls to_s for … Read more

Concatenating strings doesn’t work as expected [closed]

Your code, as written, works. You’re probably trying to achieve something unrelated, but similar: std::string c = “hello” + “world”; This doesn’t work because for C++ this seems like you’re trying to add two char pointers. Instead, you need to convert at least one of the char* literals to a std::string. Either you can do … Read more

Best practices/performance: mixing StringBuilder.append with String.concat

+ operator String s = s1 + s2 Behind the scenes this is translated to: String s = new StringBuilder(s1).append(s2).toString(); Imagine how much extra work it adds if you have s1 + s2 here: stringBuilder.append(s1 + s2) instead of: stringBuilder.append(s1).append(s2) Multiple strings with + Worth to note that: String s = s1 + s2 + … Read more

How slow is Python’s string concatenation vs. str.join?

From: Efficient String Concatenation Method 1: def method1(): out_str=”” for num in xrange(loop_count): out_str += ‘num’ return out_str Method 4: def method4(): str_list = [] for num in xrange(loop_count): str_list.append(‘num’) return ”.join(str_list) Now I realise they are not strictly representative, and the 4th method appends to a list before iterating through and joining each item, … Read more

JavaScript String concatenation behavior with null or undefined values

You can use Array.prototype.join to ignore undefined and null: [‘a’, ‘b’, void 0, null, 6].join(”); // ‘ab6’ According to the spec: If element is undefined or null, Let next be the empty String; otherwise, let next be ToString(element). Given that, What is the history behind the oddity that makes JS converting null or undefined to … Read more

String concatenation vs. string substitution in Python

Concatenation is (significantly) faster according to my machine. But stylistically, I’m willing to pay the price of substitution if performance is not critical. Well, and if I need formatting, there’s no need to even ask the question… there’s no option but to use interpolation/templating. >>> import timeit >>> def so_q_sub(n): … return “%s%s/%d” % (DOMAIN, … Read more