Skip to content

Instantly share code, notes, and snippets.

@marshluca
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marshluca/59be042e96ad74309a3d to your computer and use it in GitHub Desktop.
Save marshluca/59be042e96ad74309a3d to your computer and use it in GitHub Desktop.
benchmark on the speed of constant and class variable.
require 'benchmark'
LOCALE_ARRAY = (1..1000000).to_a
class MyClass
def self.vars
@@vars
end
def self.vars=(args)
@@vars = args if args.kind_of?(Array)
end
end
MyClass.vars = (1..1000000).to_a
n = 10,000,000,000
Benchmark.bm do |x|
x.report { LOCALE_ARRAY.include? 10240 }
x.report { MyClass.vars.include? 10240 }
x.report { LOCALE_ARRAY.find_index 10240 }
x.report { MyClass.vars.find_index 10240 }
end
╭─lucas@MacbookPro ~ ‹ruby-2.1.1›
╰─$ ruby a.rb
user system total real
0.000000 0.000000 0.000000 ( 0.000500)
0.000000 0.000000 0.000000 ( 0.000472)
0.000000 0.000000 0.000000 ( 0.000079)
0.000000 0.000000 0.000000 ( 0.000074)
╭─lucas@MacbookPro ~ ‹ruby-2.1.1›
╰─$ ruby a.rb
user system total real
0.000000 0.000000 0.000000 ( 0.000497)
0.000000 0.000000 0.000000 ( 0.000471)
0.000000 0.000000 0.000000 ( 0.000080)
0.000000 0.000000 0.000000 ( 0.000089)
╭─lucas@MacbookPro ~ ‹ruby-2.1.1›
╰─$ ruby a.rb
user system total real
0.000000 0.000000 0.000000 ( 0.000501)
0.000000 0.000000 0.000000 ( 0.000473)
0.000000 0.000000 0.000000 ( 0.000081)
0.000000 0.000000 0.000000 ( 0.000074)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment