makoto (owner)

Revisions

gist: 228715 Download_button fork
public
Public Clone URL: git://gist.github.com/228715.git
Embed All Files: show embed
Text only #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
require 'YAML'
require 'benchmark'
 
# Case 1: Global variable
 
GlobalConfig = {}
 
def get()
  if GlobalConfig[:config]
    return GlobalConfig[:config]
  else
    data = File.open('config.yml')
    GlobalConfig[:config] = YAML.load(data) # dynamic constant assignment error
    return GlobalConfig[:config]
  end
end
 
# Case 2: Instance variable
 
class ConfigReader
  def initialize(name)
    @name = name
  end
  
  def config
    @config ||= get_from_disk
  end
 
  def get_from_disk
    data = File.open('config.yml')
    YAML.load(data)
  end
end
 
config_reader = ConfigReader.new('config.yml')
 
# Case 3: Lambda
 
Config = lambda{
  data = File.open('config.yml')
  config = YAML.load(data)
}.call
 
# Benchmark
 
n = 1000000
Benchmark.bm() do |x|
  x.report("Case 1.a: Global variable ") { n.times do ; get; end }
  x.report("Case 1.b: Global variable ") { n.times do ; GlobalConfig[:config]; end }
  x.report("Case 2 : Instance variable ") { n.times do ; config_reader.config; end }
  x.report("Case 3 : Lambda ") { n.times do ; Config; end }
end
 
# Result
# user system total real
# Case 1.a: Global variable 0.670000 0.010000 0.680000 ( 0.750651)
# Case 1.b: Global variable 0.250000 0.000000 0.250000 ( 0.270964)
# Case 2 : Instance variable 0.330000 0.000000 0.330000 ( 0.376627)
# Case 3 : Lambda 0.120000 0.010000 0.130000 ( 0.153685)