Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Comparing array subset checks #125

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,32 @@ Comparison:
Array#insert: 0.2 i/s - 262.56x slower
```

##### Subset detection with various methods [code](code/array/subset-checking.rb)

```
$ ruby -v code/array/subset-checking.rb
ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux]
Warming up --------------------------------------
(a1 - a2).empty? 19.534k i/100ms
(a1 & a2) == a1 16.190k i/100ms
Array#all?#include? 27.391k i/100ms
Array#&#size 16.949k i/100ms
Set#subset? 4.289k i/100ms
Calculating -------------------------------------
(a1 - a2).empty? 206.885k (± 2.0%) i/s - 1.035M in 5.006270s
(a1 & a2) == a1 169.425k (± 2.4%) i/s - 858.070k in 5.067497s
Array#all?#include? 291.863k (± 2.1%) i/s - 1.479M in 5.070021s
Array#&#size 176.342k (± 2.9%) i/s - 898.297k in 5.098513s
Set#subset? 43.342k (± 3.0%) i/s - 218.739k in 5.051749s

Comparison:
Array#all?#include?: 291862.7 i/s
(a1 - a2).empty?: 206885.5 i/s - 1.41x slower
Array#&#size: 176341.9 i/s - 1.66x slower
(a1 & a2) == a1: 169424.9 i/s - 1.72x slower
Set#subset?: 43341.6 i/s - 6.73x slower
```

### Enumerable

##### `Enumerable#each + push` vs `Enumerable#map` [code](code/enumerable/each-push-vs-map.rb)
Expand Down
34 changes: 34 additions & 0 deletions code/array/subset-checking.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
require 'benchmark/ips'
require 'set'

ARRAY1 = [*1..25]
ARRAY2 = [*1..100]

def slow_set
ARRAY2.to_set.subset?(ARRAY1.to_set)
end

def slow_interception
(ARRAY1 & ARRAY2) == ARRAY1
end

def slow_interception_size
(ARRAY1 & ARRAY2).size == ARRAY1.size
end

def slow_minus_empty
(ARRAY1 - ARRAY2).empty?
end

def fast
ARRAY1.all?{|element| ARRAY2.include?(element) }
end

Benchmark.ips do |x|
x.report("(a1 - a2).empty?") { slow_minus_empty }
x.report("(a1 & a2) == a1") { slow_interception }
x.report("Array#all?#include?") { fast }
x.report("Array#&#size") { slow_interception_size }
x.report("Set#subset?") { slow_set }
x.compare!
end