Created
February 20, 2016 13:50
-
-
Save xander-miller/ce1ce8393fbf17ea261d to your computer and use it in GitHub Desktop.
Reverse Array performance testing by Brian Bugh
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def reverse arr | |
arr.reverse | |
end | |
def xander1 arr | |
out = [] | |
neg_i = -1 | |
arr.each do | |
out << arr[neg_i] | |
neg_i -= 1 | |
end | |
out | |
end | |
def xander2 arr | |
memory_box = '' | |
array_length = arr.length | |
(array_length/2).times do |index| | |
memory_box = arr[index] | |
arr[index] = arr[-(index + 1)] | |
arr[-(index + 1)] = memory_box | |
end | |
arr | |
end | |
def robb arr | |
arr.reduce([]) { |reversed, item| [item] + reversed } | |
end | |
def robb2 arr | |
arr.reduce([]) { |reversed, item| reversed.unshift item } | |
end | |
def robb3 arr | |
arr.reduce([]) { |reversed, item| Array.new(1, item) + reversed } | |
# arr.each_with_object([]) { |item, obj| obj.unshift item } | |
end | |
def aaron arr | |
array_length = arr.length | |
(array_length/2).times do |index| | |
inverse_index = -(index + 1) | |
arr[index], arr[inverse_index] = arr[inverse_index], arr[index] | |
end | |
arr | |
end | |
# memcpy buffer non-modifying | |
def brian1 arr | |
arr2 = arr.dup | |
pos1 = -1 | |
pos2 = length = arr2.length | |
arr2[pos2 -= 1] = arr[pos1 += 1] until ((length -= 1) < 0) | |
arr2 | |
end | |
# self-modified with memcpy buffer | |
def brian1! arr | |
arr2 = arr.dup | |
pos1 = -1 | |
pos2 = length = arr2.length | |
arr[pos2 -= 1] = arr2[pos1 += 1] until ((length -= 1) < 0) | |
arr | |
end | |
# cheese mode functional probably slow | |
def brian2 arr | |
arr.sort_by.with_index { |n, i| -i } | |
end | |
arr = (1..10000).to_a | |
count = 100 | |
require 'benchmark' | |
Benchmark.bm do |b| | |
b.report("Array#reverse") { count.times { reverse(arr) } } | |
b.report("xander1 ") { count.times { xander1(arr) } } | |
b.report("xander2 ") { count.times { xander2(arr) } } | |
# commented because it's extremely slow | |
#b.report("robb ") { count.times { robb(arr) } } | |
b.report("robb2 ") { count.times { robb2(arr) } } | |
b.report("robb3 ") { count.times { robb3(arr) } } | |
b.report("aaron ") { count.times { aaron(arr) } } | |
b.report("brian1 ") { count.times { brian1(arr) } } | |
b.report("brian1! ") { count.times { brian1!(arr) } } | |
b.report("brian2 ") { count.times { brian2(arr) } } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment