Wednesday 28 March 2012

Comparing execution time between string and symbols of ruby


Hi,
   You all must be knowing the difference between Ruby string and symbol but i want to prove a point that symbols execution time is less than string.

Try this piece of code in Pry or IRB

 require 'benchmark'

str = Benchmark.measure do
  10_000_000.times do
    "test"
  end
end.total

sym = Benchmark.measure do
  10_000_000.times do
    :test
  end
end.total


Comparing symbols is much faster than string:


require 'benchmark'

str = Benchmark.measure do
  10_000_000.times do
    "test" == "test"
  end
end.total

sym = Benchmark.measure do
  10_000_000.times do
    :test == :test
  end
end.total