Skip to content

Commit e6e318d

Browse files
committed
Add more examples to infinite loops
1 parent a9e12bc commit e6e318d

File tree

3 files changed

+58
-35
lines changed

3 files changed

+58
-35
lines changed

README.md

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -169,22 +169,28 @@ Custom exception: Kernel#raise: 589148.7 i/s
169169
Custom exception: E2MM#Raise: 29004.8 i/s - 20.31x slower
170170
```
171171

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

174174
```
175-
$ ruby -v code/general/loop-vs-while-true.rb
176-
ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-linux]
175+
$ ruby -v code/general/loop-vs-while-true-vs-until-false-vs-infinite-range.rb
176+
ruby 3.3.0dev (2023-11-12 master 60e19a0b5f) [x86_64-linux]
177177
178-
Calculating -------------------------------------
179-
While Loop 1.000 i/100ms
178+
Warming up --------------------------------------
179+
While loop 1.000 i/100ms
180180
Kernel loop 1.000 i/100ms
181-
-------------------------------------------------
182-
While Loop 0.536 (± 0.0%) i/s - 3.000 in 5.593042s
183-
Kernel loop 0.223 (± 0.0%) i/s - 2.000 in 8.982355s
181+
Infinite range 1.000 i/100ms
182+
Until loop 1.000 i/100ms
183+
Calculating -------------------------------------
184+
While loop 0.620 (± 0.0%) i/s - 4.000 in 6.451729s
185+
Kernel loop 0.274 (± 0.0%) i/s - 2.000 in 7.306426s
186+
Infinite range 0.185 (± 0.0%) i/s - 1.000 in 5.420005s
187+
Until loop 0.614 (± 0.0%) i/s - 4.000 in 6.515634s
184188
185189
Comparison:
186-
While Loop: 0.5 i/s
187-
Kernel loop: 0.2 i/s - 2.41x slower
190+
While loop: 0.6 i/s
191+
Until loop: 0.6 i/s - 1.01x slower
192+
Kernel loop: 0.3 i/s - 2.26x slower
193+
Infinite range: 0.2 i/s - 3.36x slower
188194
```
189195

190196
##### `ancestors.include?` vs `<=` [code](code/general/inheritance-check.rb)
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
require "benchmark/ips"
2+
3+
NUMBER = 100_000_000
4+
5+
def fastest
6+
index = 0
7+
while true
8+
break if index > NUMBER
9+
index += 1
10+
end
11+
end
12+
13+
def fast
14+
index = 0
15+
until false
16+
break if index > NUMBER
17+
index += 1
18+
end
19+
end
20+
21+
def slow
22+
index = 0
23+
loop do
24+
break if index > NUMBER
25+
index += 1
26+
end
27+
end
28+
29+
def slowest
30+
(0..).each do |index|
31+
break if index > NUMBER
32+
index += 1
33+
end
34+
end
35+
36+
Benchmark.ips do |x|
37+
x.report("While loop") { fastest }
38+
x.report("Until loop") { fast }
39+
x.report("Kernel loop") { slow }
40+
x.report("Infinite range") { slowest }
41+
x.compare!
42+
end

code/general/loop-vs-while-true.rb

Lines changed: 0 additions & 25 deletions
This file was deleted.

0 commit comments

Comments
 (0)