Never create Ruby strings longer than 23 characters!

Ruby

You might think it's absurd but Pat Shaughnessy found out that Ruby strings are treated differently by Ruby interpreter and the main differentiator is; wait for it, their length.

According to his blog post, he tested string creation time under Ruby 1.9.3 and apparently it's true.

We tried the same under Ruby 2.0.0-p247, more details below.

We took his exact same benchmarking code and it looks like this:

#!/usr/bin/env ruby
require 'benchmark'

ITERATIONS = 1000000

def run(str, bench)
  bench.report("#{str.length + 1} chars") do
    ITERATIONS.times do
      new_string = str + 'x'
    end
  end
end

Benchmark.bm do |bench|
  run("123456789", bench)
  run("1234567890", bench)
  run("12345678901", bench)
  run("123456789012", bench)
  run("1234567890123", bench)
  run("12345678901234", bench)
  run("123456789012345", bench)
  run("1234567890123456", bench)
  run("12345678901234567", bench)
  run("123456789012345678", bench)
  run("1234567890123456789", bench)
  run("12345678901234567890", bench)
  run("123456789012345678901", bench)
  run("1234567890123456789012", bench)
  run("12345678901234567890123", bench)
  run("123456789012345678901234", bench)
  run("1234567890123456789012345", bench)
  run("12345678901234567890123456", bench)
end

And the results were quite similar to those on MRI 1.9.3:

10 chars  0.190000   0.000000   0.190000 (  0.188447)
11 chars  0.180000   0.000000   0.180000 (  0.182217)
12 chars  0.180000   0.000000   0.180000 (  0.183564)
13 chars  0.190000   0.000000   0.190000 (  0.181764)
14 chars  0.180000   0.000000   0.180000 (  0.183241)
15 chars  0.180000   0.000000   0.180000 (  0.184435)
16 chars  0.190000   0.000000   0.190000 (  0.186187)
17 chars  0.200000   0.000000   0.200000 (  0.197703)
18 chars  0.180000   0.000000   0.180000 (  0.184525)
19 chars  0.190000   0.000000   0.190000 (  0.187837)
20 chars  0.190000   0.000000   0.190000 (  0.187393)
21 chars  0.180000   0.000000   0.180000 (  0.183598)
22 chars  0.190000   0.000000   0.190000 (  0.188693)
23 chars  0.190000   0.000000   0.190000 (  0.189455)
24 chars  0.300000   0.000000   0.300000 (  0.305304)
25 chars  0.310000   0.000000   0.310000 (  0.307249)
26 chars  0.310000   0.000000   0.310000 (  0.309091)
27 chars  0.310000   0.000000   0.310000 (  0.314742)

Quite dazzling but true. So, next time you create Ruby strings, watch out!