Skip to content

Commit

Permalink
Merge pull request #127 from carlos-contreras/format-vs-round-and-to-s
Browse files Browse the repository at this point in the history
Add benchmark for format() vs round().to_s
  • Loading branch information
Arcovion authored Jun 7, 2017
2 parents 3e74a66 + f3e8b1c commit 279401e
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,27 @@ Comparison:
OpenStruct: 96855.3 i/s - 16.56x slower
```

##### Kernel#format vs Float#round().to_s [code](code/general/format-vs-round-and-to-s.rb)

```
$ ruby -v code/general/format-vs-round-and-t
o-s.rb
ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-darwin15]
Warming up --------------------------------------
Float#round 106.645k i/100ms
Kernel#format 84.304k i/100ms
String#% 78.635k i/100ms
Calculating -------------------------------------
Float#round 1.570M (± 3.2%) i/s - 7.892M in 5.030672s
Kernel#format 1.144M (± 3.0%) i/s - 5.733M in 5.015621s
String#% 1.047M (± 4.2%) i/s - 5.269M in 5.042970s
Comparison:
Float#round: 1570411.4 i/s
Kernel#format: 1144036.6 i/s - 1.37x slower
String#%: 1046689.1 i/s - 1.50x slower
```

### Array

##### `Array#bsearch` vs `Array#find` [code](code/array/bsearch-vs-find.rb)
Expand Down
22 changes: 22 additions & 0 deletions code/general/format-vs-round-and-to-s.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
require 'benchmark/ips'

NUM = 1.12678.freeze

def fast
NUM.round(2).to_s
end

def avg
format('%.2f', NUM)
end

def slow
'%.2f' % NUM
end

Benchmark.ips do |x|
x.report('Float#round') { fast }
x.report('Kernel#format') { avg }
x.report('String#%') { slow }
x.compare!
end

0 comments on commit 279401e

Please sign in to comment.