mirror of
https://github.com/golang/go
synced 2024-11-22 00:54:43 -07:00
container/ring: Replace Iter() with Do().
Faster in most cases, and not prone to memory leaks. Named "Do" to match with similarly named method on Vector. R=gri CC=golang-dev https://golang.org/cl/4134046
This commit is contained in:
parent
5e83d40904
commit
3629d72328
@ -138,16 +138,13 @@ func (r *Ring) Len() int {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
func (r *Ring) Iter() <-chan interface{} {
|
// Do calls function f on each element of the ring, in forward order.
|
||||||
c := make(chan interface{})
|
// The behavior of Do is undefined if f changes *r.
|
||||||
go func() {
|
func (r *Ring) Do(f func(interface{})) {
|
||||||
if r != nil {
|
if r != nil {
|
||||||
c <- r.Value
|
f(r.Value)
|
||||||
for p := r.Next(); p != r; p = p.next {
|
for p := r.Next(); p != r; p = p.next {
|
||||||
c <- p.Value
|
f(p.Value)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
close(c)
|
}
|
||||||
}()
|
|
||||||
return c
|
|
||||||
}
|
}
|
||||||
|
@ -35,12 +35,12 @@ func verify(t *testing.T, r *Ring, N int, sum int) {
|
|||||||
// iteration
|
// iteration
|
||||||
n = 0
|
n = 0
|
||||||
s := 0
|
s := 0
|
||||||
for p := range r.Iter() {
|
r.Do(func(p interface{}) {
|
||||||
n++
|
n++
|
||||||
if p != nil {
|
if p != nil {
|
||||||
s += p.(int)
|
s += p.(int)
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
if n != N {
|
if n != N {
|
||||||
t.Errorf("number of forward iterations == %d; expected %d", n, N)
|
t.Errorf("number of forward iterations == %d; expected %d", n, N)
|
||||||
}
|
}
|
||||||
@ -128,16 +128,6 @@ func makeN(n int) *Ring {
|
|||||||
return r
|
return r
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
func sum(r *Ring) int {
|
|
||||||
s := 0
|
|
||||||
for p := range r.Iter() {
|
|
||||||
s += p.(int)
|
|
||||||
}
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
func sumN(n int) int { return (n*n + n) / 2 }
|
func sumN(n int) int { return (n*n + n) / 2 }
|
||||||
|
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user