Quick method performance checker

With ruby there are often many ways to perform the same operation. Recently I learned that the * operator can act like join for strings.
I wanted to do a little performance check to see if one is faster than the other.

Using ruby blocks, I wrote up a timed_run method:

def timed_run(*args, &block)
  t = Time.now
  block.call
  dt = (Time.now - t)
  puts "[#{args.first}] #{dt}msec"
end

With this helper, I then wrote up several methods to test joining strings with separators:

def join_with_join(arr, sep)
  arr.join sep
end

def join_with_times(arr, sep)
  arr * sep
end

def join_with_plus(arr, sep)
  val = ''
  arr.each{|a| val += sep if val.length > 0; val += a }
  val
end

def join_with_append(arr, sep)
  val = ''
  arr.each{|a| val << sep if val.length > 0; val << a }
  val
end

Putting this all together, I was able to test my different join implementations for performance:

def gen_random_string
  # exercise for reader
end

num_runs = 100000
arr = (25 + rand(4)).times.map{ gen_random_string }
sep = " , "
%w(join_with_plus join_with_times join_with_join join_with_append).each do |meth|
  timed_run(meth) { num_runs.times { send(meth, arr, sep) }}
end

and very quickly see that the * and join operators are basically the same
in terms of performance. And I learned that the << is slow but much faster than +.

[join_with_append] 1.19829msec
[join_with_join] 0.436115msec
[join_with_times] 0.431106msec
[join_with_plus] 4.26063msec

It's a nice usage of the call method and Ruby blocks. I learned a few tricks and now i have a nice little timer script that I can use to test other implementations of other algorithms.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s