Skip to content

Instantly share code, notes, and snippets.

@danini-the-panini
Last active March 11, 2022 07:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danini-the-panini/883baaa92c4dc4f8ed1a49134600576c to your computer and use it in GitHub Desktop.
Save danini-the-panini/883baaa92c4dc4f8ed1a49134600576c to your computer and use it in GitHub Desktop.
reject! vs next
require 'benchmark/ips'
N = 1_000_000
ARRAY = N.times.map { rand }
Benchmark.ips do |x|
x.report("reject") do
arr = ARRAY.dup
out = []
arr.reject! { _1 >= 0.5 }
arr.each { out << _1 }
end
x.report("next") do
arr = ARRAY.dup
out = []
arr.each { next if _1 >= 0.5; out << _1 }
end
x.hold! 'temp_results'
x.compare!
end
Warming up --------------------------------------
reject 2.000 i/100ms
next 2.000 i/100ms
Calculating -------------------------------------
reject 20.503 (± 0.0%) i/s - 104.000 in 5.072750s
next 25.475 (± 0.0%) i/s - 128.000 in 5.025467s
Comparison:
next: 25.5 i/s
reject: 20.5 i/s - 1.24x (± 0.00) slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment