Skip to content

Commit fb7e06e

Browse files
authored
Merge pull request #151 from bdewater/string-dup-vs-unary-plus
Add comparison for unfreezing strings in `frozen_string_literal: true` files
2 parents 7d52e31 + 99e47c3 commit fb7e06e

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

README.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -930,6 +930,24 @@ Comparison:
930930

931931
### String
932932

933+
##### `String#dup` vs `String#+` [code](code/string/dup-vs-unary-plus.rb)
934+
935+
Note that `String.new` is not the same as the options compared, since it is
936+
always `ASCII-8BIT` encoded instead of the script encoding (usually `UTF-8`).
937+
938+
```
939+
$ ruby -v code/string/dup-vs-unary-plus.rb
940+
ruby 2.4.3p205 (2017-12-14 revision 61247) [x86_64-darwin17]
941+
942+
Calculating -------------------------------------
943+
String#+@ 7.697M (± 1.4%) i/s - 38.634M in 5.020313s
944+
String#dup 3.566M (± 1.0%) i/s - 17.860M in 5.008377s
945+
946+
Comparison:
947+
String#+@: 7697108.3 i/s
948+
String#dup: 3566485.7 i/s - 2.16x slower
949+
```
950+
933951
##### `String#casecmp` vs `String#downcase + ==` [code](code/string/casecmp-vs-downcase-==.rb)
934952

935953
```

code/string/dup-vs-unary-plus.rb

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# frozen_string_literal: true
2+
3+
require 'benchmark/ips'
4+
5+
if RUBY_VERSION >= '2.3.0'
6+
def fast
7+
+''
8+
end
9+
10+
def slow
11+
''.dup
12+
end
13+
14+
Benchmark.ips do |x|
15+
x.report('String#+@') { fast }
16+
x.report('String#dup') { slow }
17+
x.compare!
18+
end
19+
end

0 commit comments

Comments
 (0)