Skip to content

Instantly share code, notes, and snippets.

@bittersweet
Created December 14, 2012 09:53
Show Gist options
  • Save bittersweet/4284187 to your computer and use it in GitHub Desktop.
Save bittersweet/4284187 to your computer and use it in GitHub Desktop.
Quick Benchmark to check what kind of array 'slicing' performs well
require 'benchmark'
class User
def initialize
@instance_var = rand(100)
end
end
users = []
10000.times do |i|
users.push User.new
end
SPLIT_AT = users.size / 2
# Using bmbm to account for GC
# http://www.ruby-doc.org/stdlib-1.9.3/libdoc/benchmark/rdoc/Benchmark.html
Benchmark.bmbm do |b|
b.report('next: ') do
users.each_with_index do |user, index|
next if users.index(user) > SPLIT_AT
local_var = user
end
end
b.report('reject: ') do
users.reject{|i| users.index(i) > SPLIT_AT}.each do |user|
local_var = user
end
end
b.report('range: ') do
users[0..SPLIT_AT].each do |user|
local_var = user
end
end
b.report('first(n): ') do
users.first(SPLIT_AT).each do |user|
local_var = user
end
end
b.report('shift(n): ') do
users.shift(SPLIT_AT).each do |user|
local_var = user
end
end
end
Rehearsal ----------------------------------------------
next: 3.520000 0.070000 3.590000 ( 3.839394)
reject: 3.560000 0.090000 3.650000 ( 3.812247)
range: 0.000000 0.000000 0.000000 ( 0.000587)
first(n): 0.000000 0.000000 0.000000 ( 0.000601)
shift(n): 0.000000 0.000000 0.000000 ( 0.000541)
------------------------------------- total: 7.240000sec
user system total real
next: 0.880000 0.010000 0.890000 ( 0.914190)
reject: 0.920000 0.010000 0.930000 ( 0.945588)
range: 0.000000 0.000000 0.000000 ( 0.000700)
first(n): 0.000000 0.000000 0.000000 ( 0.000709)
shift(n): 0.000000 0.000000 0.000000 ( 0.000683)
require 'benchmark'
ARRAY = 1.upto(1000000).to_a
SPLIT_AT = 500000
# Using bmbm to account for GC
Benchmark.bmbm do |b|
b.report('next: ') do
ARRAY.each do |i|
next if i > SPLIT_AT
local_var = i
end
end
b.report('reject: ') do
ARRAY.reject{|i| i > SPLIT_AT}.each do |i|
local_var = i
end
end
b.report('range: ') do
ARRAY[0..SPLIT_AT].each do |i|
local_var = i
end
end
b.report('first(n): ') do
ARRAY.first(SPLIT_AT).each do |i|
local_var = i
end
end
b.report('shift(n): ') do
ARRAY.shift(SPLIT_AT).each do |i|
local_var = i
end
end
end
Rehearsal ----------------------------------------------
next: 0.110000 0.010000 0.120000 ( 0.120553)
reject: 0.150000 0.010000 0.160000 ( 0.169044)
range: 0.060000 0.000000 0.060000 ( 0.067574)
first(n): 0.050000 0.000000 0.050000 ( 0.053314)
shift(n): 0.050000 0.000000 0.050000 ( 0.055513)
------------------------------------- total: 0.440000sec
user system total real
next: 0.060000 0.000000 0.060000 ( 0.063703)
reject: 0.050000 0.000000 0.050000 ( 0.058155)
range: 0.050000 0.000000 0.050000 ( 0.054786)
first(n): 0.050000 0.000000 0.050000 ( 0.057561)
shift(n): 0.060000 0.010000 0.070000 ( 0.058572)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment