Skip to content

Instantly share code, notes, and snippets.

@tsnow
Created September 29, 2011 14:26
Show Gist options
  • Save tsnow/1250830 to your computer and use it in GitHub Desktop.
Save tsnow/1250830 to your computer and use it in GitHub Desktop.
>> x = (1..10000000).to_a; x.length
=> 10000000
>>
?> by_reverse = Proc.new{|p,o| Proc.new{|a,b| b.send(p,o) <=> a.send(p,o)}}
=> #<Proc:0x000000013b68a330@(irb):50>
>> Benchmark.bm do |y|
?> y.report("sort_by neg") { x.sort_by{|i| - (i + 1)} }
>> y.report("sort no_send") { x.sort{|a,b| (b + 1) <=> (a + 1)} }
>> y.report("sort send") { x.sort{|a,b| b.send('+', 1) <=> a.send('+', 1)}}
>> y.report('procs send') { x.sort(&(by_reverse.call('+',1))) }
>> y.report('sort_by send reverse') { x.sort_by{|i| i.send('+', 1)}.reverse}
>> y.report('sort_by reverse') { x.sort_by{|i| (i + 1)}.reverse }
>> end
user system total real
sort_by neg 6.140000 0.030000 6.170000 ( 6.169397)
sort no_send 8.500000 0.040000 8.540000 ( 8.533514)
sort send 11.880000 0.040000 11.920000 ( 11.930224)
procs send 11.080000 0.040000 11.120000 ( 11.115269)
sort_by send reverse 7.590000 0.020000 7.610000 ( 7.607284)
sort_by reverse 5.410000 0.030000 5.440000 ( 5.441332)
=> true
>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment