Skip to content

Commit 4b42f95

Browse files
committed
Remove Hash#[] from tests
1 parent 68ad9dd commit 4b42f95

File tree

2 files changed

+7
-16
lines changed

2 files changed

+7
-16
lines changed

README.md

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -805,25 +805,21 @@ Comparison:
805805
Hash#keys.each: 869262.3 i/s - 1.21x slower
806806
```
807807

808-
#### `Hash#key?` vs. `Hash#[]` vs. `Hash#keys.include?` [code](code/hash/keys-include-vs-\[\]-vs-key.rb)
808+
#### `Hash#key?` instead of `Hash#keys.include?` [code](code/hash/keys-include-vs-\[\]-vs-key.rb)
809809

810810
> `Hash#keys.include?` allocates an array of keys and performs an O(n) search; <br>
811-
> `Hash#key?` performs an O(1) hash lookup without allocating a new array; <br>
812-
> `Hash#[]` performs an O(1) hash lookup as well.
811+
> `Hash#key?` performs an O(1) hash lookup without allocating a new array.
813812
814813
```
815-
$ ruby -v code/hash/keys-include-vs-\[\]-vs-key.rb
816-
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-darwin17]
814+
$ ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-darwin17]
817815
818816
Calculating -------------------------------------
819-
Hash#keys.include? 8.293k (± 6.1%) i/s - 41.964k in 5.083215s
820-
Hash#[] 6.412M (± 3.1%) i/s - 32.160M in 5.020295s
821-
Hash#key? 6.616M (± 5.0%) i/s - 33.178M in 5.030955s
817+
Hash#keys.include? 8.612k (± 2.5%) i/s - 43.248k in 5.024749s
818+
Hash#key? 6.366M (± 5.5%) i/s - 31.715M in 5.002276s
822819
823820
Comparison:
824-
Hash#key?: 6615589.2 i/s
825-
Hash#[]: 6412217.3 i/s - same-ish: difference falls within error
826-
Hash#keys.include?: 8293.2 i/s - 797.71x slower
821+
Hash#key?: 6365855.5 i/s
822+
Hash#keys.include?: 8612.4 i/s - 739.15x slower
827823
```
828824

829825
##### `Hash#value?` instead of `Hash#values.include?` [code](code/hash/values-include-vs-value.rb)

code/hash/keys-include-vs-[]-vs-key.rb renamed to code/hash/keys-include-vs-key.rb

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,12 @@ def key_fast
77
HASH.key? KEY
88
end
99

10-
def key_resolve
11-
!!HASH[KEY]
12-
end
13-
1410
def key_slow
1511
HASH.keys.include? KEY
1612
end
1713

1814
Benchmark.ips do |x|
1915
x.report("Hash#keys.include?") { key_slow }
20-
x.report("Hash#[]") { key_resolve }
2116
x.report("Hash#key?") { key_fast }
2217
x.compare!
2318
end

0 commit comments

Comments
 (0)