File tree Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -1155,6 +1155,25 @@ String#chomp'string': 2803443.5 i/s
1155
1155
String#sub/regexp/: 660508.7 i/s - 4.24x slower
1156
1156
```
1157
1157
1158
+ ##### ` String#unpack1 ` vs ` String#unpack[0] ` [ code] ( code/string/unpack1-vs-unpack[0].rb )
1159
+
1160
+ [ Ruby 2.4.0 introduced ` unpack1 ` ] ( https://bugs.ruby-lang.org/issues/12752 ) to skip creating the intermediate array object.
1161
+
1162
+ ```
1163
+ $ ruby -v code/string/unpack1-vs-unpack\[0\].rb
1164
+ ruby 2.4.3p205 (2017-12-14 revision 61247) [x86_64-darwin17]
1165
+ Warming up --------------------------------------
1166
+ String#unpack1 224.291k i/100ms
1167
+ String#unpack[0] 201.870k i/100ms
1168
+ Calculating -------------------------------------
1169
+ String#unpack1 4.864M (± 4.2%) i/s - 24.448M in 5.035203s
1170
+ String#unpack[0] 3.778M (± 4.0%) i/s - 18.976M in 5.031253s
1171
+
1172
+ Comparison:
1173
+ String#unpack1: 4864467.2 i/s
1174
+ String#unpack[0]: 3777815.6 i/s - 1.29x slower
1175
+ ```
1176
+
1158
1177
##### Remove extra spaces (or other contiguous characters) [ code] ( code/string/remove-extra-spaces-or-other-chars.rb )
1159
1178
1160
1179
The code is tested against contiguous spaces but should work for other chars too.
Original file line number Diff line number Diff line change
1
+ require 'benchmark/ips'
2
+
3
+ if RUBY_VERSION >= '2.4.0'
4
+ STRING = "foobarbaz" . freeze
5
+
6
+ def fast
7
+ STRING . unpack1 ( 'h*' )
8
+ end
9
+
10
+ def slow
11
+ STRING . unpack ( 'h*' ) [ 0 ]
12
+ end
13
+
14
+ Benchmark . ips do |x |
15
+ x . report ( 'String#unpack1' ) { fast }
16
+ x . report ( 'String#unpack[0]' ) { slow }
17
+ x . compare!
18
+ end
19
+ end
You can’t perform that action at this time.
0 commit comments