Skip to content

Commit

Permalink
reduce object allocations
Browse files Browse the repository at this point in the history
Example:

x = [1,2,3,4]
y = [3,2,1]

def test x, y
  hash = {}
  x.zip(y) { |k,v| hash[k] = v }
  hash
end

def test2 x, y
  Hash[x.zip(y)]
end

def test3 x, y
  x.zip(y).each_with_object({}) { |(k,v),hash| hash[k] = v }
end

def stat num
  start = GC.stat(:total_allocated_object)
  num.times { yield }
  total_obj_count = GC.stat(:total_allocated_object) - start
  puts "#{total_obj_count / num} allocations per call"
end

stat(100) { test(x,y) }
stat(100) { test2(x,y) }
stat(100) { test3(x,y) }

__END__
2 allocations per call
7 allocations per call
8 allocations per call
  • Loading branch information
tenderlove committed May 21, 2014
1 parent da83a6f commit 931ee41
Showing 1 changed file with 4 additions and 2 deletions.
6 changes: 4 additions & 2 deletions actionpack/lib/action_dispatch/routing/route_set.rb
Expand Up @@ -184,7 +184,7 @@ def call(t, args)
private

def optimized_helper(args)
params = Hash[parameterize_args(args)]
params = parameterize_args(args)
missing_keys = missing_keys(params)

unless missing_keys.empty?
Expand All @@ -203,7 +203,9 @@ def optimize_routes_generation?(t)
end

def parameterize_args(args)
@required_parts.zip(args.map(&:to_param))
params = {}
@required_parts.zip(args.map(&:to_param)) { |k,v| params[k] = v }
params
end

def missing_keys(args)
Expand Down

0 comments on commit 931ee41

Please sign in to comment.