Skip to content

Commit

Permalink
Add more examples to infinite loops
Browse files Browse the repository at this point in the history
  • Loading branch information
ydakuka committed Dec 10, 2023
1 parent a9e12bc commit e6e318d
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 35 deletions.
26 changes: 16 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,22 +169,28 @@ Custom exception: Kernel#raise: 589148.7 i/s
Custom exception: E2MM#Raise: 29004.8 i/s - 20.31x slower
```

##### `loop` vs `while true` [code](code/general/loop-vs-while-true.rb)
##### `loop` vs `while true` vs `until false` vs `infinite range` [code](code/general/loop-vs-while-true-vs-until-false-vs-infinite-range.rb)

```
$ ruby -v code/general/loop-vs-while-true.rb
ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-linux]
$ ruby -v code/general/loop-vs-while-true-vs-until-false-vs-infinite-range.rb
ruby 3.3.0dev (2023-11-12 master 60e19a0b5f) [x86_64-linux]
Calculating -------------------------------------
While Loop 1.000 i/100ms
Warming up --------------------------------------
While loop 1.000 i/100ms
Kernel loop 1.000 i/100ms
-------------------------------------------------
While Loop 0.536 (± 0.0%) i/s - 3.000 in 5.593042s
Kernel loop 0.223 (± 0.0%) i/s - 2.000 in 8.982355s
Infinite range 1.000 i/100ms
Until loop 1.000 i/100ms
Calculating -------------------------------------
While loop 0.620 (± 0.0%) i/s - 4.000 in 6.451729s
Kernel loop 0.274 (± 0.0%) i/s - 2.000 in 7.306426s
Infinite range 0.185 (± 0.0%) i/s - 1.000 in 5.420005s
Until loop 0.614 (± 0.0%) i/s - 4.000 in 6.515634s
Comparison:
While Loop: 0.5 i/s
Kernel loop: 0.2 i/s - 2.41x slower
While loop: 0.6 i/s
Until loop: 0.6 i/s - 1.01x slower
Kernel loop: 0.3 i/s - 2.26x slower
Infinite range: 0.2 i/s - 3.36x slower
```

##### `ancestors.include?` vs `<=` [code](code/general/inheritance-check.rb)
Expand Down
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
25 changes: 0 additions & 25 deletions code/general/loop-vs-while-true.rb

This file was deleted.

0 comments on commit e6e318d

Please sign in to comment.