From: "Jesús Gabriel y Galán" Date: 2008-03-31T17:17:04+09:00 Subject: Re: Help on best way to gather/sort results ? On Sun, Mar 30, 2008 at 3:47 PM, Todd Benson wrote: > On Sat, Mar 29, 2008 at 8:45 PM, Tony De wrote: > > Thanks Jesus & Todd for your posts also. I appreciate the education. > > Forums are great for getting real world experience on language usage and > > gotcha's. So I do have another question on my sort. I realize that in > > addition to the sort on the second element in each row of my array > > (sourceip) I would also like to then sort on the third element (email). > > So my current sort is: > > > > > > @results.sort! {|x, y| y[1] <=> x[1]} > > > > So this now sorts first by element[2] and then by element[3]: > > new_results = @results.sort_by { |x| [x[1], x[2]] } > > > > There are so many ways to accomplish the same result. That dosen't > > mean, however, it's the most efficient. Would there be a more efficient > > way to do this? Not that this script is costing me a great deal in > > resources. But it nice to code tight when possible. Thanks again. > > > On my machine... > > a = [[3, 2, 1], [4, 5, 6], [1, 5, 7], [1, 2, 3]] > > t = Time.now > 10_000.times do > > a.sort_by {|x| [x[1], x[2]]} > end > puts Time.now - t > > t = Time.now > 10_000.times do > a.sort {|x,y| [x[1], x[2]] <=> [y[1], y[2]]} > end > puts Time.now - t > > 10_000.times do > a.sort! {|x,y| [x[1], x[2]] <=> [y[1], y[2]]} > end > puts Time.now - t > > => 0.25 #sort_by > => 0.453 #sort > => 0.859 #sort! > > > This may be due to the creation of addition Array objects within the block. The difference between sort and sort_by is that sort calls the block every time it needs to make a comparison between two elements, passing both elements. sort_by, on the other hand, calls the block once for each element in the array, and calculates and records the sort value for each element. Then it performs the sorting algorithm against those values. So, when is one more efficient than the other depends on the length of the array (well, the number of comparisons made by the sorting algorithm) and the cost of calculating the sort value. Jesus.