Skip to content

Instantly share code, notes, and snippets.

@josh-works
Last active April 13, 2018 17:45
Show Gist options
  • Save josh-works/4ab5f7fd1c2d835586eb03145b472f7e to your computer and use it in GitHub Desktop.
Save josh-works/4ab5f7fd1c2d835586eb03145b472f7e to your computer and use it in GitHub Desktop.
ruby, benchmarking, double_inject

Double inject. What does it mean?

i want to know how long it takes to do some stuff. I've got some code like this:

def count_stuff(list)
  list.inject([]) do |results, item|
    results << get_results_from_something_else(values)
  end.flatten.uniq
end

def get_results_from_something_else(item)
  item.inject([]) do |results, item_value|
    results << do_database_work(item_value)
  end
end

So, these seems like a massive anti-pattern. This is basically a double inject, and some of the objects we're working with could contain tens of thousands of items. It seems like running this could cause a lot of memory consumption.

So, we're going to see exactly how expensive this operation is.

Ruby Benchmark

This code should be simple enough that you can copy-paste into your own editor, and get these results. Lets go!

This is making use of the Benchmark API

require 'benchmark'

run_quantity = 500000

Benchmark.bm do |bm|
  # using join
  bm.report do
    run_quantity.times do
      ["the", "current", "time", "is", Time.now].join(" ")
    end
  end


  bm.report do
    # using string interpolation
    run_quantity.times do
      "the current time is #{Time.now}"
    end
  end
end

Run the file, and you'll get something like this:

       user     system      total        real
   1.900000   0.090000   1.990000 (  2.285985)
   1.520000   0.080000   1.600000 (  2.473372)

I borrowed the above example from dzone: "How do I Benchmark Ruby Code"

Here's my current work:

require 'benchmark'

run_quantity = 500
numbers = Array.new(100) { rand(1...10000) }
p numbers

Benchmark.bmbm(20) do |bm|
  # using join
  bm.report('single inject') do
    run_quantity.times do
      numbers.inject([]) do |results, num|
        results << num if num % 2 == 0
        results
      end.sort
    end
  end
end

Resources

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