-
Notifications
You must be signed in to change notification settings - Fork 375
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
58 additions
and
35 deletions.
There are no files selected for viewing
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
42 changes: 42 additions & 0 deletions
42
code/general/loop-vs-while-true-vs-until-false-vs-infinite-range.rb
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
require "benchmark/ips" | ||
|
||
NUMBER = 100_000_000 | ||
|
||
def fastest | ||
index = 0 | ||
while true | ||
break if index > NUMBER | ||
index += 1 | ||
end | ||
end | ||
|
||
def fast | ||
index = 0 | ||
until false | ||
break if index > NUMBER | ||
index += 1 | ||
end | ||
end | ||
|
||
def slow | ||
index = 0 | ||
loop do | ||
break if index > NUMBER | ||
index += 1 | ||
end | ||
end | ||
|
||
def slowest | ||
(0..).each do |index| | ||
break if index > NUMBER | ||
index += 1 | ||
end | ||
end | ||
|
||
Benchmark.ips do |x| | ||
x.report("While loop") { fastest } | ||
x.report("Until loop") { fast } | ||
x.report("Kernel loop") { slow } | ||
x.report("Infinite range") { slowest } | ||
x.compare! | ||
end |
This file was deleted.
Oops, something went wrong.