Skip to content

Commit ffc26bd

Browse files
committed
[Set] Replace defer (R)Unlock() with direct calling
in plain simple methods to speedup Set Signed-off-by: Anton Tiurin <[email protected]>
1 parent d6145b6 commit ffc26bd

File tree

2 files changed

+46
-4
lines changed

2 files changed

+46
-4
lines changed

set/dict.go

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,11 @@ func (set *Set) Remove(items ...interface{}) {
5959
// Exists returns a bool indicating if the given item exists in the set.
6060
func (set *Set) Exists(item interface{}) bool {
6161
set.lock.RLock()
62-
defer set.lock.RUnlock()
6362

6463
_, ok := set.items[item]
64+
65+
set.lock.RUnlock()
66+
6567
return ok
6668
}
6769

@@ -84,17 +86,21 @@ func (set *Set) Flatten() []interface{} {
8486
// Len returns the number of items in the set.
8587
func (set *Set) Len() int64 {
8688
set.lock.RLock()
87-
defer set.lock.RUnlock()
8889

89-
return int64(len(set.items))
90+
size := int64(len(set.items))
91+
92+
set.lock.RUnlock()
93+
94+
return size
9095
}
9196

9297
// Clear will remove all items from the set.
9398
func (set *Set) Clear() {
9499
set.lock.Lock()
95-
defer set.lock.Unlock()
96100

97101
set.items = map[interface{}]struct{}{}
102+
103+
set.lock.Unlock()
98104
}
99105

100106
// All returns a bool indicating if all of the supplied items exist in the set.

set/dict_test.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,3 +176,39 @@ func BenchmarkFlatten(b *testing.B) {
176176
set.Flatten()
177177
}
178178
}
179+
180+
func BenchmarkLen(b *testing.B) {
181+
set := New()
182+
for i := 0; i < 50; i++ {
183+
item := strconv.Itoa(i)
184+
set.Add(item)
185+
}
186+
187+
b.ResetTimer()
188+
for i := 0; i < b.N; i++ {
189+
set.Len()
190+
}
191+
}
192+
193+
func BenchmarkExists(b *testing.B) {
194+
set := New()
195+
set.Add(1)
196+
197+
b.ResetTimer()
198+
for i := 0; i < b.N; i++ {
199+
set.Exists(1)
200+
}
201+
}
202+
203+
func BenchmarkClear(b *testing.B) {
204+
set := New()
205+
for i := 0; i < 50; i++ {
206+
item := strconv.Itoa(i)
207+
set.Add(item)
208+
}
209+
210+
b.ResetTimer()
211+
for i := 0; i < b.N; i++ {
212+
set.Clear()
213+
}
214+
}

0 commit comments

Comments
 (0)