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

Micro-optimizing Ruby

Micro-optimizing Ruby

A talk originally given to the Dallas Ruby Brigade and then re-presented as an online lunch and learn.

https://www.youtube.com/watch?v=3HpjZPbBS-s

Aaron Lasseigne

October 01, 2015
Tweet

More Decks by Aaron Lasseigne

Other Decks in Programming

Transcript

  1. Bigger Optimizations • SQL queries • n + 1 queries

    • Ruby version • server software • server configuration • caching • sharding Smarter Co-workers
  2. pry> 10.times { 'hello' } Total allocated: 400 bytes (10

    objects) pry> h = {} pry> 10.times { h['hello'] } Total allocated: 40 bytes (1 objects)
  3. pry> [2, 4, 6].select!(&:even?) => nil pry> [2, 4, 6].keep_if(&:even?)

    => [2, 4, 6] pry> [2, 4, 6].reject!(&:odd?) => nil pry> [2, 4, 6].delete_if(&:odd?) => [2, 4, 6]
  4. We can make it better! keys.each map {}.flatten reverse.each each.with_index

    each.with_object each_key reverse_each each_with_object each_with_index flat_map {}
  5. Calculating ------------------------------------- String#=~ 56.672k i/100ms String#start_with? 118.308k i/100ms ------------------------------------------------- String#=~

    919.574k (± 6.4%) i/s - 4.590M String#start_with? 4.177M (± 6.4%) i/s - 20.822M Comparison: String#start_with?: 4177162.6 i/s String#=~: 919574.2 i/s - 4.54x slower
  6. Calculating ------------------------------------- fast 85.749k i/100ms slow 35.529k i/100ms ------------------------------------------------- fast

    1.867M (± 7.6%) i/s - 9.347M slow 467.095k (± 6.4%) i/s - 2.345M Comparison: fast: 1866669.5 i/s slow: 467095.4 i/s - 4.00x slower