Created
July 3, 2023 20:57
-
-
Save noteflakes/d48bb74737577d1e7e6ab3954270325a to your computer and use it in GitHub Desktop.
Which is faster, loop or while?
This file contains 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
# 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