Step 3: Add BigDecimal from a number vs from a String (#172) · fastruby/fast-ruby@7d1b8df · GitHub
Skip to content

Commit 7d1b8df

Browse files
JuanVqzbdewater
andcommitted
Step 3: Add BigDecimal from a number vs from a String (#172)
From #172 by @bdewater: the ways to build a BigDecimal, from a String or from the number, for an integer and a float value. Changes to the PR's file: - Split into integer-string-vs-numeric.rb and float-string-vs-numeric.rb. The PR's single file had 8 reports, more than the 6 rank names, and mixed two questions (String vs number, integer vs float). Each file now has 4 reports that all return the same value. - Named by what current Rubies measure, which is the opposite of the PR's 2019 run on Ruby 2.5: on CRuby 3.4, 4.0 and head, BigDecimal(1) is 1.7x to 2.1x faster than BigDecimal('1'), and BigDecimal(1.0, 2) is the fastest float form. Strings still win on Ruby 2.1, and for floats on JRuby. The comments only state the Ruby 4.0 result; the README shows every version. Two more: the String forms parse the String the same way, so they tie, and a Float needs the precision argument on Rubies before 4.0 (BigDecimal(1.0) raises on 2.1 and 3.4). The README entry keeps the PR's Ruby 2.5.3 sample, with a note that it ran both files as one, and adds runs of each file on Ruby 2.5, 3.4 and 4.0.7. bigdecimal loads on every Ruby tried (2.1, 3.4, 4.0, head, JRuby head, TruffleRuby head), so the Gemfile does not change. Co-authored-by: Bart de Water <496367+bdewater@users.noreply.github.com>
1 parent 928a618 commit 7d1b8df

3 files changed

Lines changed: 219 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 160 additions & 0 deletions
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
require 'benchmark/ips'
2+
require 'bigdecimal'
3+
require 'bigdecimal/util'
4+
5+
# On Ruby 4.0, building from the Float is about 1.3x faster than from a String.
6+
# The precision argument (2) is there for older Rubies, where BigDecimal(1.0) raises "can't omit precision for a Float".
7+
def faster
8+
BigDecimal(1.0, 2)
9+
end
10+
11+
def fast
12+
1.0.to_d
13+
end
14+
15+
# BigDecimal('1.0') and '1.0'.to_d parse the String the same way, so these two should tie.
16+
def slow
17+
BigDecimal('1.0')
18+
end
19+
20+
def slower
21+
'1.0'.to_d
22+
end
23+
24+
Benchmark.ips do |x|
25+
x.report('float new') { faster }
26+
x.report('float to_d') { fast }
27+
x.report('float string new') { slow }
28+
x.report('float string to_d') { slower }
29+
x.compare!
30+
end
Lines changed: 29 additions & 0 deletions

0 commit comments

Comments
 (0)