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

Micro Performance Improvements

Micro Performance Improvements

A few changes that you can do to your code to make it have a faster performance

Ernesto Tagwerker

April 26, 2017
Tweet

More Decks by Ernesto Tagwerker

Other Decks in Technology

Transcript

  1. Benchmark.ips do |x| OBJECT = "nil".freeze x.report("unless nil") do true

    unless OBJECT.nil? end x.report("if object") do true if OBJECT end x.compare! end
  2. $ bundle exec ruby benchmarks/unless_nil_vs_if_object.rb Ruby version: 2.3.3 Warming up

    -------------------------------------- unless nil 251.994k i/100ms if object 267.552k i/100ms Calculating ------------------------------------- unless nil 9.435M (± 6.9%) i/s - 47.123M in 5.021124s if object 11.431M (± 4.9%) i/s - 57.256M in 5.021363s Comparison: if object: 11431148.2 i/s unless nil: 9435226.8 i/s - 1.21x slower
  3. # OK phone = Hash.new(number: number) phone[:number] # Better Phone

    = Struct.new(:number) phone = Phone.new(number) phone.number
  4. $ bundle exec ruby benchmarks/struct_vs_hash.rb Ruby version: 2.3.3 Warming up

    -------------------------------------- struct 22.148k i/100ms hash 4.688k i/100ms Calculating ------------------------------------- struct 240.460k (± 2.7%) i/s - 1.218M in 5.069592s hash 47.926k (± 3.9%) i/s - 243.776k in 5.094413s Comparison: struct: 240459.9 i/s hash: 47926.1 i/s - 5.02x slower
  5. $ bundle exec ruby benchmarks/time/parse_vs_at.rb Ruby version: 2.3.3 Warming up

    -------------------------------------- Time.parse 3.287k i/100ms Time.at 66.086k i/100ms Calculating ------------------------------------- Time.parse 34.052k (± 3.2%) i/s - 170.924k in 5.024737s Time.at 842.576k (± 2.2%) i/s - 4.230M in 5.022207s Comparison: Time.at: 842576.2 i/s Time.parse: 34051.9 i/s - 24.74x slower
  6. $ bundle exec rake benches:pluck_vs_map Ruby version: 2.3.3 Warming up

    -------------------------------------- map(&:id) 11.000 i/100ms pluck(:id) 80.000 i/100ms Calculating ------------------------------------- map(&:id) 124.205 (±11.3%) i/s - 616.000 in 5.026999s pluck(:id) 807.127 (± 2.0%) i/s - 4.080k in 5.057062s Comparison: pluck(:id): 807.1 i/s map(&:id): 124.2 i/s - 6.50x slower