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.

1f74b13f1e5c6c69cb5d7fbaabb1e2cb?s=128

Erik Berlin

October 13, 2014
Tweet

Transcript

  1. 1.
  2. 2.
  3. 3.
  4. 4.
  5. 6.

    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)
  6. 7.
  7. 8.

    Benchmark require ‘benchmark' n = 50 Benchmark.bm do |x| x.report

    { n.times { fast } } x.report { n.times { slow } } end
  8. 9.

    Benchmark require ‘benchmark' n = 50_000 Benchmark.bm do |x| x.report

    { n.times { fast } } x.report { n.times { slow } } end
  9. 11.

    Goals Source Significant Easy Happy Optimize at the code level

    At least 12% improvement Code should be easier to read High quality Ruby
  10. 17.
  11. 18.
  12. 21.
  13. 22.
  14. 25.
  15. 26.

    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
  16. 28.
  17. 29.
  18. 32.
  19. 33.
  20. 34.

    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
  21. 36.

    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
  22. 46.

    Using exceptions for control flow begin ruby.conf rescue NoMethodError 'conf'

    end if ruby.respond_to?(:conf) ruby.conf else 'conf' end
  23. 48.

    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
  24. 51.
  25. 52.
  26. 53.
  27. 54.
  28. 55.
  29. 56.

    Special Thanks Aaron Patterson Ruby Rogues Parley Sam Saffron Aman

    Gupta Don Knuth Yukihiro Matsumoto Koichi Sasada RubyConf Portugal
  30. 57.
  31. 58.