Slow Ruby for simple array operations

I created a simple implementation of insertion sort in Ruby, following the pseudo-code from Cormen's Introduction to Algorithms:

def sort_insert(array) (1 ... array.length).each do |item_index| key = array[item_index] i = item_index - 1 while i >= 0 && array[i] > key do array[i + 1] = array[i] i -= 1 end array[i + 1] = key end array end 

It works, but it works very slowly. For an array of ~ 20k elements, array = ((0..10_000).to_a * 2).shuffle takes about 20 seconds to sort. I only measure time for this method call, data preparation, etc. In JavaScript, a very similar solution takes about 1 second. Why is Ruby (v.2.2.2p95) so slow here?

Edit: The JS version of this sort that I use:

 function SortMethods() { } SortMethods.prototype.sortInsert = function(array) { for(let itemIndex = 1; itemIndex < array.length; itemIndex++) { let key = array[itemIndex]; let i = itemIndex - 1; while( i >= 0 && array[i] > key) { array[i + 1] = array[i]; i--; } array[i + 1] = key; } return array; } 
+6
source share
1 answer

I am going to disagree with the premise of your question. Ruby is turning more than decent work into my car.

To illustrate this, I created a file with 100k random numbers:

 $ ruby -e '100_000.times {printf "%22.20f\n", rand}' > rand100k.csv 

Then I sorted this using the system sort utility, saving the results for later comparison (as a validation):

 $ time sort -n < rand100k.csv > foo real 0m0.067s user 0m0.056s sys 0m0.011s 

I wrote a quick sort algorithm (which is flipped to sort the insert when the sublist size is small enough) in a pure ruby, run it, save the results, and distinguish between the system sort output and the ruby ​​output files:

 $ time ruby quicksort_w_insertion.rb < rand100k.csv > bar real 0m0.546s user 0m0.537s sys 0m0.008s $ diff foo bar $ 

As you can see, both sorts trigger identical output and very quickly. In my opinion, a pure Ruby program, which is only 8-10 times slower than the corresponding system utility, makes a powerful damn thin speed.

These runs were performed using ruby 2.2.2p95 (2015-04-13 revision 50293) [x86_64-darwin14] on the MacBook Pro.

0
source

All Articles