Skip to content

Commit 9b74279

Browse files
authored
Merge pull request #148 from bdewater/unpack1
Add String#unpack1 vs String#unpack[0]
2 parents 17b089d + a403654 commit 9b74279

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

.travis.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ cache: bundler
33
bundler_args: --retry=3 --jobs=3
44
language: ruby
55
rvm:
6+
- 2.4.3
67
- 2.3.0
78
- 2.1.8
89
- 2.2.4

README.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1155,6 +1155,25 @@ String#chomp'string': 2803443.5 i/s
11551155
String#sub/regexp/: 660508.7 i/s - 4.24x slower
11561156
```
11571157

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+
11581177
##### Remove extra spaces (or other contiguous characters) [code](code/string/remove-extra-spaces-or-other-chars.rb)
11591178

11601179
The code is tested against contiguous spaces but should work for other chars too.
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
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

0 commit comments

Comments
 (0)