Ruby speed quiz

For each case choose the fastest option.

Platform, which hosted this quiz was closed. So it will be read only for some time.

1. Range cover? VS include?

('a'..'z').include?('f')
('a'..'z').cover?('f')
  1. both run with similar speed

2. blk.call VS yield

def foo
  yield if block_given?
end
foo { puts "Hi from foo" }
  1. both run with similar speed

def bar(&blk)
  blk.call
end
bar { puts "Hi from bar" }

3. Hash [] VS fetch

h = {}
h[:a] || 1
h = {}
h.fetch(:a, 1)
  1. both run with similar speed

4. super with OR without arguments

class Parent
  def bar(a, b)
    puts "#{a} - #{b}"
  end
end

class Child < Parent
  def bar(a, b)
    super(a, b)
  end
end
c = Child.new
c.bar(1, 2)
  1. both run with similar speed

class Parent
 def bar(a, b)
   puts "#{a} - #{b}"
 end
end

class Child < Parent
 def bar(a, b)
   super
 end
end
c = Child.new
c.bar(1, 2)

5. define_method VS class_eval (definition, NOT call speed)

class A
  100.times do |i|
    define_method("foo_#{i}") { 10.times.map { "foo".length } }
  end
end
class B
  100.times do |i|
    class_eval 'def bar_#{i}; 10.times.map { "foo".length };
end'
  end
end
  1. both run with similar speed

Check yourself:

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

Here you could find an explanation for each case.

Comments

comments powered by Disqus