Skip to content

Instantly share code, notes, and snippets.

@deepak
Created October 11, 2010 10:35
Show Gist options
  • Save deepak/620326 to your computer and use it in GitHub Desktop.
Save deepak/620326 to your computer and use it in GitHub Desktop.
ruby_constant_lookup_cache_benchmark.rb
# ruby caches the const lookup like method lookup
# due to this no need to explicitly memonize in code
# although, i think eval will break this cache
# TODO: what will clear the const/method cache
# http://yehudakatz.com/2010/02/25/rubys-implementation-does-not-define-its-semantics/
require 'benchmark'
LOGGER = 10
module Foo
module Bar
Benchmark.bm { |x|
x.report("access_once") { LOGGER }
x.report("access_once_more") { LOGGER }
x.report("access_again_1") { LOGGER }
x.report("access_again_2") { LOGGER }
x.report("access_again_3") { LOGGER }
x.report("access_else") { 10.times { LOGGER } }
x.report("access_last") { LOGGER }
}
module Again1
module Again2
module Again3
module Again4
module Again5
module Again6
Benchmark.bm { |x|
# is the same as 'access_once_more', uses the cached value
x.report("access_inside_once") { LOGGER }
x.report("access_inside_once_more") { LOGGER }
x.report("access_inside_again_1") { LOGGER }
x.report("access_inside_again_2") { LOGGER }
x.report("access_inside_again_3") { LOGGER }
}
end
end
end
end
end
end
end
end
module Foo
remove_const :Bar
end
module Foo
module Bar
Logger = 20
Benchmark.bm { |x|
x.report("access_once") { LOGGER }
# puts LOGGER
x.report("access_once_more") { LOGGER }
x.report("access_again_1") { LOGGER }
x.report("access_again_2") { LOGGER }
x.report("access_again_3") { LOGGER }
x.report("access_else") { 10.times { LOGGER } }
x.report("access_last") { LOGGER }
}
module Again1
module Again2
module Again3
module Again4
module Again5
module Again6
LOGGER = 30
Benchmark.bm { |x|
# time-taken is less than 'access_once' as the const is nearer in the lookup chain
# thereafter it is cached
x.report("access_inside_once") { LOGGER }
# puts LOGGER
x.report("access_inside_once_more") { LOGGER }
x.report("access_inside_again_1") { LOGGER }
x.report("access_inside_again_2") { LOGGER }
x.report("access_inside_again_3") { LOGGER }
}
end
end
end
end
end
end
end
end
__END__
task "resque:setup" => :environment do
require 'stdout_logger'
logger = StdoutLogger.new_logger
Kernel.const_set(:RESQUE_LOGGER, logger)
ActiveRecord::Base.logger = logger
Kernel.const_set(:RAILS_DEFAULT_LOGGER, logger)
end
class ResqueTask
def logger
RESQUE_LOGGER
end
def self.logger
RESQUE_LOGGER
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment