Skip to content

Instantly share code, notes, and snippets.

@noteflakes
Created July 3, 2023 20:57
Show Gist options
  • Save noteflakes/d48bb74737577d1e7e6ab3954270325a to your computer and use it in GitHub Desktop.
Save noteflakes/d48bb74737577d1e7e6ab3954270325a to your computer and use it in GitHub Desktop.
Which is faster, loop or while?
# frozen_string_literal: true
require "benchmark/ips"
def loop_run(count)
x = 0
loop do
x += 1
break if x >= count
end
end
def while_run(count)
x = 0
while x < count
x += 1
end
end
COUNT = 10000
Benchmark.ips do |x|
x.report('loop') { loop_run(COUNT) }
x.report('while') { while_run(COUNT) }
x.compare!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment