File tree Expand file tree Collapse file tree 2 files changed +43
-0
lines changed Expand file tree Collapse file tree 2 files changed +43
-0
lines changed Original file line number Diff line number Diff line change @@ -268,6 +268,27 @@ Comparison:
268
268
OpenStruct: 96855.3 i/s - 16.56x slower
269
269
```
270
270
271
+ ##### Kernel#format vs Float#round().to_s [ code] ( code/general/format-vs-round-and-to-s.rb )
272
+
273
+ ```
274
+ $ ruby -v code/general/format-vs-round-and-t
275
+ o-s.rb
276
+ ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-darwin15]
277
+ Warming up --------------------------------------
278
+ Float#round 106.645k i/100ms
279
+ Kernel#format 84.304k i/100ms
280
+ String#% 78.635k i/100ms
281
+ Calculating -------------------------------------
282
+ Float#round 1.570M (± 3.2%) i/s - 7.892M in 5.030672s
283
+ Kernel#format 1.144M (± 3.0%) i/s - 5.733M in 5.015621s
284
+ String#% 1.047M (± 4.2%) i/s - 5.269M in 5.042970s
285
+
286
+ Comparison:
287
+ Float#round: 1570411.4 i/s
288
+ Kernel#format: 1144036.6 i/s - 1.37x slower
289
+ String#%: 1046689.1 i/s - 1.50x slower
290
+ ```
291
+
271
292
### Array
272
293
273
294
##### ` Array#bsearch ` vs ` Array#find ` [ code] ( code/array/bsearch-vs-find.rb )
Original file line number Diff line number Diff line change
1
+ require 'benchmark/ips'
2
+
3
+ NUM = 1.12678 . freeze
4
+
5
+ def fast
6
+ NUM . round ( 2 ) . to_s
7
+ end
8
+
9
+ def avg
10
+ format ( '%.2f' , NUM )
11
+ end
12
+
13
+ def slow
14
+ '%.2f' % NUM
15
+ end
16
+
17
+ Benchmark . ips do |x |
18
+ x . report ( 'Float#round' ) { fast }
19
+ x . report ( 'Kernel#format' ) { avg }
20
+ x . report ( 'String#%' ) { slow }
21
+ x . compare!
22
+ end
You can’t perform that action at this time.
0 commit comments