Pleaee quote when replying Daniel A. wrote in post #968730: > Thanks Marnen. > > I think the times are only related to the time taken to execute the SQL > query, not to put that in memory and then sort the array.
You're right that the times don't include in-memory sorting. But on reflection, those times are ActiveRecord load times. That means they most likely include the time to retrieve records from the DB -- and then to instantiate Ruby objects for each record! Try this experiment: run those two queries from your favorite database client, outside of Rails. See if the time difference persists. > > In the first case, I'm curious about how MySQL can sort all the elements > so > fast. Why not look up the MySQL source code and find out? > I've read > (http://www.igvita.com/2009/03/26/ruby-algorithms-sorting-trie-heaps/) > that > Ruby's Array sort method implementation is pretty good. It uses Quick > Sort. > I've tried to to sort an array of strings an another one of integers, > already sorted both of them, with *irb* and the result it's > almost instantaneous. Maybe MySQL uses quick sort too.. Perhaps. It probably has other tricks. > > About the second query you say it has to sort the users in the opposite > order which MySQL should take the same amount of time than before, but > this > is not the case. I see what you mean about Ruby, but I think that time > is > only for MySQL. See above. > > About the third and fourth queries, I've compared both results with > queries > one and two and I get the same array. Sure, you will sometimes, but there's no guarantee. > Why would the DB return the > records in > an unpredictable order? Because that's the way SQL databases work. The records within each table have no intrinsic ordering, and the DB is allowed to return them to you in whatever order it likes, unless you specify otherwise. If you need a particular order, then you always, without exception, need to specify what that order is. > > > In the Wikipedia <http://en.wikipedia.org/wiki/Quicksort>, the right > sidebar > explains the reason why Quick Sort is slow when the set is already > sorted. > Oh, this is also a pretty nice > website<http://www.sorting-algorithms.com/reversed-initial-order>, > it has animations of different sort algorithms. I'll check those out. I do not think, however, that the difference in time you're seeing is due to sort algorithms as such. Best, -- Marnen Laibow-Koser http://www.marnen.org [email protected] Sent from my iPhone -- Posted via http://www.ruby-forum.com/. -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

