From 1273f69e74a96696e7ec1143dc15d72111c0c7de Mon Sep 17 00:00:00 2001 From: Eric Wong Date: Fri, 4 Sep 2009 13:48:41 -0700 Subject: [PATCH 1/3] HeaderHash.new avoids unnecessary object creation Creating a new HeaderHash is an O(n) operation in addition to the cost of allocating a new object. When using multiple pieces of middleware, this can lead to unnecessary memory allocation and iteration overhead. We now explicitly define the HeaderHash.new class method to return its original argument if it is already a HeaderHash to avoid repeating work. --- lib/rack/utils.rb | 4 ++++ test/spec_rack_utils.rb | 8 ++++++++ 2 files changed, 12 insertions(+), 0 deletions(-) diff --git a/lib/rack/utils.rb b/lib/rack/utils.rb index 74303ef..21b58c9 100644 --- a/lib/rack/utils.rb +++ b/lib/rack/utils.rb @@ -258,6 +258,10 @@ module Rack # A case-insensitive Hash that preserves the original case of a # header when set. class HeaderHash < Hash + def self.new(hash={}) + HeaderHash === hash ? hash : super(hash) + end + def initialize(hash={}) super() @names = {} diff --git a/test/spec_rack_utils.rb b/test/spec_rack_utils.rb index c397429..3586f8c 100644 --- a/test/spec_rack_utils.rb +++ b/test/spec_rack_utils.rb @@ -268,6 +268,14 @@ context "Rack::Utils::HeaderHash" do h = Rack::Utils::HeaderHash.new("foo" => "bar") h.delete("Hello").should.be.nil end + + specify "should avoid unnecessary object creation if possible" do + a = Rack::Utils::HeaderHash.new("foo" => "bar") + b = Rack::Utils::HeaderHash.new(a) + b.object_id.should.equal(a.object_id) + b.should.equal(a) + end + end context "Rack::Utils::Context" do -- 1.6.4.2.236.gf324c