Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Writing Fast Ruby

Writing Fast Ruby

Originally presented at Baruco 2014. Updated for RubyConf Portugal 2014.

Video here: https://www.youtube.com/watch?v=fGFM_UrSp70.

Erik Berlin

October 13, 2014
Tweet

More Decks by Erik Berlin

Other Decks in Programming

Transcript

  1. Levels of Optimization Design Source Build Compile Runtime Architecture and

    algorithms (e.g. n + 1 queries) Writing fast Ruby Setting build flags (e.g. ./configure) mrbc, jrubyc, rbx compile Thanks Matz & Koichi (e.g. RUBY_GC_MALLOC_LIMIT)
  2. Benchmark require ‘benchmark' n = 50 Benchmark.bm do |x| x.report

    { n.times { fast } } x.report { n.times { slow } } end
  3. Benchmark require ‘benchmark' n = 50_000 Benchmark.bm do |x| x.report

    { n.times { fast } } x.report { n.times { slow } } end
  4. Goals Source Significant Easy Happy Optimize at the code level

    At least 12% improvement Code should be easier to read High quality Ruby
  5. Hash#keys and Enumerable#each
 versus Hash#each_key hash.keys.each do |k| # do

    something end hash.each_key do |k| # do something end
  6. Hash#merge versus Hash#merge! enum.inject({}) do |h, e| h.merge(e => e)

    end enum.inject({}) do |h, e| h.merge!(e => e) end
  7. Hash#merge! versus Hash#[]= enum.each_with_object({}) do |e, h| h.merge!(e => e)

    end enum.each_with_object({}) do |e, h| h[e] = e end
  8. Using exceptions for control flow begin ruby.conf rescue NoMethodError 'conf'

    end if ruby.respond_to?(:conf) ruby.conf else 'conf' end
  9. Using throw/catch for control flow begin ruby.conf rescue NoMethodError 'conf'

    end catch(:ruby) do if ruby.respond_to?(:conf) ruby.conf else throw(:ruby, ‘conf’) end end
  10. Special Thanks Aaron Patterson Ruby Rogues Parley Sam Saffron Aman

    Gupta Don Knuth Yukihiro Matsumoto Koichi Sasada RubyConf Portugal