Commit 5a5bc9e
committed
Optimize Number generators with arithmetic instead of string building
- number: generate the whole value with a single ranged rand instead of
concatenating per-digit strings and re-parsing with to_i.
- leading_zero_number: one rand plus rjust instead of one digit call per
position; also handle digits < 2 explicitly.
- decimal: build the right-hand side arithmetically (rand * 10 +
non_zero_digit) instead of joining a per-digit array.
- hexadecimal/binary: append with << into a pre-sized String instead of
+= which reallocates the string on every iteration.
Benchmark (Ruby 3.4.9, arm64-darwin25, benchmark-ips):
require 'benchmark/ips'
require 'faker'
Benchmark.ips do |x|
x.config(warmup: 1, time: 2)
x.report('number(digits: 10)') { Faker::Number.number(digits: 10) }
x.report('leading_zero_number(digits: 10)') { Faker::Number.leading_zero_number(digits: 10) }
x.report('decimal(5, 5)') { Faker::Number.decimal(l_digits: 5, r_digits: 5) }
x.report('hexadecimal(digits: 32)') { Faker::Number.hexadecimal(digits: 32) }
x.report('binary(digits: 32)') { Faker::Number.binary(digits: 32) }
end
Results:
main: number(digits: 10) 516.487k (+/- 1.8%) i/s
leading_zero_number(digits: 10) 532.109k (+/- 4.2%) i/s
decimal(5, 5) 439.388k (+/- 2.0%) i/s
hexadecimal(digits: 32) 177.646k (+/- 0.9%) i/s
binary(digits: 32) 170.770k (+/- 0.8%) i/s
this commit: number(digits: 10) 4.823M (+/- 3.4%) i/s (~9.3x)
leading_zero_number(digits: 10) 4.551M (+/- 1.4%) i/s (~8.6x)
decimal(5, 5) 1.663M (+/- 1.4%) i/s (~3.8x)
hexadecimal(digits: 32) 230.063k (+/- 1.2%) i/s (~1.3x)
binary(digits: 32) 220.621k (+/- 1.1%) i/s (~1.3x)1 parent 9b07803 commit 5a5bc9e
1 file changed
Lines changed: 9 additions & 7 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
18 | 18 | | |
19 | 19 | | |
20 | 20 | | |
21 | | - | |
| 21 | + | |
22 | 22 | | |
23 | 23 | | |
24 | 24 | | |
| |||
32 | 32 | | |
33 | 33 | | |
34 | 34 | | |
35 | | - | |
| 35 | + | |
| 36 | + | |
| 37 | + | |
36 | 38 | | |
37 | 39 | | |
38 | 40 | | |
| |||
71 | 73 | | |
72 | 74 | | |
73 | 75 | | |
74 | | - | |
| 76 | + | |
75 | 77 | | |
76 | 78 | | |
77 | 79 | | |
| |||
113 | 115 | | |
114 | 116 | | |
115 | 117 | | |
116 | | - | |
117 | | - | |
| 118 | + | |
| 119 | + | |
118 | 120 | | |
119 | 121 | | |
120 | 122 | | |
| |||
128 | 130 | | |
129 | 131 | | |
130 | 132 | | |
131 | | - | |
132 | | - | |
| 133 | + | |
| 134 | + | |
133 | 135 | | |
134 | 136 | | |
135 | 137 | | |
| |||
0 commit comments