File tree 2 files changed +46
-0
lines changed
2 files changed +46
-0
lines changed Original file line number Diff line number Diff line change @@ -1329,6 +1329,24 @@ Comparison:
1329
1329
String#gsub: 516604.2 i/s - 3.60x slower
1330
1330
```
1331
1331
1332
+ ##### ` String#gsub ` vs ` String#tr ` vs ` String#del ` [ code] ( code/string/gsub-vs-tr-vs-del.rb )
1333
+
1334
+ ```
1335
+ ruby 2.2.0p0 (2014-12-25 revision 49005) [x86_64-linux]
1336
+
1337
+ Calculating -------------------------------------
1338
+ String#gsub 1.342M (± 1.3%) i/s - 6.816M in 5.079675s
1339
+ String#tr 2.627M (± 1.0%) i/s - 13.387M in 5.096083s
1340
+ String#delete 2.924M (± 0.7%) i/s - 14.889M in 5.093070s
1341
+ String#delete const 3.136M (± 2.6%) i/s - 15.866M in 5.064043s
1342
+
1343
+ Comparison:
1344
+ String#delete const: 3135559.1 i/s
1345
+ String#delete: 2923531.8 i/s - 1.07x slower
1346
+ String#tr: 2627150.5 i/s - 1.19x slower
1347
+ String#gsub: 1342013.4 i/s - 2.34x slower
1348
+ ```
1349
+
1332
1350
##### ` Mutable ` vs ` Immutable ` [ code] ( code/string/mutable_vs_immutable_strings.rb )
1333
1351
1334
1352
```
Original file line number Diff line number Diff line change
1
+ require 'benchmark/ips'
2
+
3
+ WORDS = 'writing fast ruby'
4
+ SPACE = ' '
5
+
6
+ def use_gsub
7
+ WORDS . gsub ( ' ' , '' )
8
+ end
9
+
10
+ def use_tr
11
+ WORDS . tr ( ' ' , '' )
12
+ end
13
+
14
+ def use_delete
15
+ WORDS . delete ( ' ' )
16
+ end
17
+
18
+ def use_delete_const
19
+ WORDS . delete ( SPACE )
20
+ end
21
+
22
+ Benchmark . ips do |x |
23
+ x . report ( 'String#gsub' ) { use_gsub }
24
+ x . report ( 'String#tr' ) { use_tr }
25
+ x . report ( 'String#delete' ) { use_delete }
26
+ x . report ( 'String#delete const' ) { use_delete_const }
27
+ x . compare!
28
+ end
You can’t perform that action at this time.
0 commit comments