Skip to content

Instantly share code, notes, and snippets.

@nevans
Created October 25, 2011 22:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nevans/1314531 to your computer and use it in GitHub Desktop.
Save nevans/1314531 to your computer and use it in GitHub Desktop.
premature micro-optimizations are the root of all evil

ruby 1.8.7 (REE)

irb(main):031:0> start = Time.now; 10_000_000.times { 'foo' }; puts Time.now - start
=> 2.154165
irb(main):032:0> start = Time.now; 10_000_000.times { "foo" }; puts Time.now - start
=> 2.177029

Remind me again, why do I care about 23 milliseconds for every 10 million string loads? Methinks that just one instance of needing to change single quotes to double quotes so you can do some interpolation that you hadn't originally foreseen will take more time than a month of ruby loading double quotes, unless its on some superduper hyper sensitive performance critical inner loop (in which case, are you sure ruby is the right language for you?). Am I wrong?

Oh, and how about other versions of ruby?

ruby 1.9.3-rc1:

irb(main):002:0> start = Time.now; 10_000_000.times { "foo" }; Time.now - start
=> 1.551125075
irb(main):003:0> start = Time.now; 10_000_000.times { 'foo' }; Time.now - start
=> 1.535057393

Again, why do I care about 16 milliseconds for every 10 million string loads?

Rubinius 2.0.0-dev:

irb(main):004:0> start = Time.now; 10_000_000.times { 'foo' }; Time.now - start
=> 0.745409
irb(main):005:0> start = Time.now; 10_000_000.times { "foo" }; Time.now - start
=> 0.807167

This is the biggest difference yet. An awe inspiring 55 milliseconds per 10 million string loads. Again, a single instance of changing to double quotes because of an unforeseen interpolation will erase that entire performance penalty.

JRuby 1.6.4:

irb(main):003:0> start = Time.now; 10_000_000.times { "foo" }; Time.now - start
=> 0.743
irb(main):004:0> start = Time.now; 10_000_000.times { 'foo' }; Time.now - start
=> 0.757

Not only is JRuby just plain faster overall, it's also faster for double quotes than single quotes!

In conclusion

These benchmarks are complete BS. If you have profiled actual production code and see a significant speedup in a performance critical section, then go ahead and make the change.

But I like my default design choices to be useful. I like to optimize for the programmers first and the computer second.

Anyway, if you really care about pre-optimizing microseconds: use double quotes by default and switch to JRuby.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment