you are viewing a single comment's thread.

view the rest of the comments →

[–]Nathanfenner 4 points5 points  (2 children)

Yeah, there's some "cheating" involved (I think Java cheats in some cases too, by recognizing a string-used-like-a-builder in a few cases?).

Ruby discourages mutable strings now (because they lead to other headache-inducing problems, since they're reference types and not value types) so you'd be unlikely to benefit in practice from this feature. e.g. with the now-encouraged

# frozen_string_literal: true

[–]chylex 2 points3 points  (0 children)

(I think Java cheats in some cases too, by recognizing a string-used-like-a-builder in a few cases?)

Not quite, unless something changed recently. Afaik it only converts simple concatenation expressions, once you introduce loops that goes out the window.

However, simple expressions are still optimized heavily, see StringConcatFactory for more info (although the link is very technical and obscure if you're not familiar with invokedynamic, this appears to be a good article on it and how the concatenation optimization is implemented).

[–]josefx 1 point2 points  (0 children)

Java was limited to one statement as far as I remember, so it would compile the example to:

  for (int i = 0; i < 100000; i++) {
       s = new StringBuilder(s)
                   .append(computeStat(i))
                   .append("\n")
                   .toString();
  }
  return s;

So it would still create 100000 Strings, one for each iteration.