tiny optimisations of dag.Set

1. Use hint for map size in Set.Copy().
2. Use Set.Copy() if Set.Difference() argument is empty.
This commit is contained in:
Sergey Elantsev 2021-04-09 22:59:30 +03:00
parent 1212bbec9f
commit 1ad01debf3
2 changed files with 15 additions and 6 deletions

View File

@ -56,13 +56,13 @@ func (s Set) Intersection(other Set) Set {
// Difference returns a set with the elements that s has but // Difference returns a set with the elements that s has but
// other doesn't. // other doesn't.
func (s Set) Difference(other Set) Set { func (s Set) Difference(other Set) Set {
if other == nil || other.Len() == 0 {
return s.Copy()
}
result := make(Set) result := make(Set)
for k, v := range s { for k, v := range s {
var ok bool if _, ok := other[k]; !ok {
if other != nil {
_, ok = other[k]
}
if !ok {
result.Add(v) result.Add(v)
} }
} }
@ -105,7 +105,7 @@ func (s Set) List() []interface{} {
// Copy returns a shallow copy of the set. // Copy returns a shallow copy of the set.
func (s Set) Copy() Set { func (s Set) Copy() Set {
c := make(Set) c := make(Set, len(s))
for k, v := range s { for k, v := range s {
c[k] = v c[k] = v
} }

View File

@ -31,6 +31,12 @@ func TestSetDifference(t *testing.T) {
[]interface{}{3, 2, 1, 4}, []interface{}{3, 2, 1, 4},
[]interface{}{}, []interface{}{},
}, },
{
"B is nil",
[]interface{}{1, 2, 3},
nil,
[]interface{}{1, 2, 3},
},
} }
for i, tc := range cases { for i, tc := range cases {
@ -44,6 +50,9 @@ func TestSetDifference(t *testing.T) {
for _, v := range tc.B { for _, v := range tc.B {
two.Add(v) two.Add(v)
} }
if tc.B == nil {
two = nil
}
for _, v := range tc.Expected { for _, v := range tc.Expected {
expected.Add(v) expected.Add(v)
} }