rubygems/rubygems — pull request #545 by tenderlove (2013-04-23 17:51:57+00:00)
Title: cache dup logic to speed up Gem::Specification#initialize

Gem::Specification#initialize is a hotspot when booting Rails. This PR caches the "dup" logic in the initialize method for a speed bump on init. This diff speeds up initialization by about 20% (depending on if GC is on or off).

Here's my benchmark:

```ruby
require 'benchmark/ips'

class AaronSpec < Gem::Specification
@@default_value_init = {}

@@default_value.each_with_object({}) { |(k,v), h|
lookup = case v
when Time, Numeric, Symbol, true, false, nil
lambda { v }
else
lambda { v.dup }
end
@@default_value_init[k] = lookup
}

def default_value_init name
@@default_value_init[name].call
end

def initialize name = nil, version = nil
@loaded = false
@activated = false
self.loaded_from = nil
@original_platform = nil

@@nil_attributes.each do |key|
instance_variable_set "@#{key}", nil
end

@@non_nil_attributes.each do |key|
value = default_value_init(key)
instance_variable_set "@#{key}", value
end

@new_platform = Gem::Platform::RUBY

self.name = name if name
self.version = version if version

yield self if block_given?
end
end

GC.disable

Benchmark.ips do |x|
x.report("aaron") { AaronSpec.new }
x.report("original") { Gem::Specification.new }
end

__END__
Calculating -------------------------------------
aaron 2195 i/100ms
original 1746 i/100ms
-------------------------------------------------
aaron 22236.2 (±7.3%) i/s - 111945 in 5.068976s
original 16947.0 (±7.8%) i/s - 85554 in 5.085530s

```