Skip to content

Instantly share code, notes, and snippets.

@slavikdev
Created November 7, 2011 13:37
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 slavikdev/1344982 to your computer and use it in GitHub Desktop.
Save slavikdev/1344982 to your computer and use it in GitHub Desktop.
Demonstration of the code execution difference in speed when class, object and local variables are used.
# Demonstration of the code execution difference in speed when class, object and local variables are used.
# This example shows class variables performing much much worst, perhaps due to internal synchronization within Ruby engine.
# I've recently noticed that issue, profiling my code, so I don't really know the reason.
# The PI calculation algorithm has been taken somewhere and might be not best, but that's not the point.
# Results:
# MRI 1.9.3
# user system total real
# @@class => 434.228000 0.063000 434.291000 (437.134613)
# @object => 200.243000 0.031000 200.274000 (202.477156)
# local => 132.492000 0.000000 132.492000 (133.706739)
#
# JRuby 1.6.5
# user system total real
# @@class => 183.354000 0.000000 183.354000 (183.174000)
# @object => 65.529000 0.000000 65.529000 ( 65.529000)
# local => 20.658000 0.000000 20.658000 ( 20.658000)
require 'benchmark'
class PiClass
class << self
def calculate
@@num = 4.0
@@pi = 0
@@plus = true
@@den = 1
while @@den < 10000000
if @@plus
@@pi = @@pi + @@num/@@den
@@plus = false
else
@@pi = @@pi - @@num/@@den
@@plus = true
end
@@den += 2
end
@@pi
end
end
end
class PiObject
def calculate
@num = 4.0
@pi = 0
@plus = true
@den = 1
while @den < 10000000
if @plus
@pi = @pi + @num/@den
@plus = false
else
@pi = @pi - @num/@den
@plus = true
end
@den += 2
end
@pi
end
end
class PiLocal
def calculate
num = 4.0
pi = 0
plus = true
den = 1
while den < 10000000
if plus
pi = pi + num/den
plus = false
else
pi = pi - num/den
plus = true
end
den += 2
end
pi
end
end
N = 100
Benchmark.bm do |x|
print '@@class => '
x.report { N.times { PiClass.calculate } }
print '@object => '
pi_obj = PiObject.new
x.report { N.times { pi_obj.calculate } }
print 'local => '
pi_loc = PiLocal.new
x.report { N.times { pi_loc.calculate } }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment