Sorting an array of strings in Ruby -
i have learned 2 array sorting methods in ruby:
array = ["one", "two", "three"] array.sort.reverse!
or:
array = ["one", "two", "three"] array.sort { |x,y| y<=>x }
and not able differentiate between two. method better , how different in execution?
both lines same (create new array, reverse sorted). main argument readability , performance. array.sort.reverse!
more readable array.sort{|x,y| y<=>x}
- think can agree here.
for performance part, created quick benchmark script, gives following on system (ruby 1.9.3p392 [x86_64-linux]
):
user system total real array.sort.reverse 1.330000 0.000000 1.330000 ( 1.334667) array.sort.reverse! 1.200000 0.000000 1.200000 ( 1.198232) array.sort!.reverse! 1.200000 0.000000 1.200000 ( 1.199296) array.sort{|x,y| y<=>x} 5.220000 0.000000 5.220000 ( 5.239487)
run times pretty constant multiple executions of benchmark script.
array.sort.reverse
(with or without !
) way faster array.sort{|x,y| y<=>x}
. thus, recommend that.
here script reference:
#!/usr/bin/env ruby require 'benchmark' benchmark.bm do|b| master = (1..1_000_000).map(&:to_s).shuffle = master.dup b.report("array.sort.reverse ") a.sort.reverse end = master.dup b.report("array.sort.reverse! ") a.sort.reverse! end = master.dup b.report("array.sort!.reverse! ") a.sort!.reverse! end = master.dup b.report("array.sort{|x,y| y<=>x} ") a.sort{|x,y| y<=>x} end end
Comments
Post a Comment