Skip to content

perf: avoid unnecessary copy operation #3376

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

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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
21 changes: 12 additions & 9 deletions ring.go
Original file line number Diff line number Diff line change
Expand Up @@ -349,17 +349,16 @@ func (c *ringSharding) newRingShards(
return
}

// Warning: External exposure of `c.shards.list` may cause data races.
// So keep internal or implement deep copy if exposed.
func (c *ringSharding) List() []*ringShard {
var list []*ringShard

c.mu.RLock()
if !c.closed {
list = make([]*ringShard, len(c.shards.list))
copy(list, c.shards.list)
}
c.mu.RUnlock()
defer c.mu.RUnlock()

return list
if c.closed {
return nil
}
return c.shards.list
}

func (c *ringSharding) Hash(key string) string {
Expand Down Expand Up @@ -423,6 +422,7 @@ func (c *ringSharding) Heartbeat(ctx context.Context, frequency time.Duration) {
case <-ticker.C:
var rebalance bool

// note: `c.List()` return a shadow copy of `[]*ringShard`.
for _, shard := range c.List() {
err := shard.Client.Ping(ctx).Err()
isUp := err == nil || err == pool.ErrPoolTimeout
Expand Down Expand Up @@ -582,6 +582,7 @@ func (c *Ring) retryBackoff(attempt int) time.Duration {

// PoolStats returns accumulated connection pool stats.
func (c *Ring) PoolStats() *PoolStats {
// note: `c.List()` return a shadow copy of `[]*ringShard`.
shards := c.sharding.List()
var acc PoolStats
for _, shard := range shards {
Expand Down Expand Up @@ -651,6 +652,7 @@ func (c *Ring) ForEachShard(
ctx context.Context,
fn func(ctx context.Context, client *Client) error,
) error {
// note: `c.List()` return a shadow copy of `[]*ringShard`.
shards := c.sharding.List()
var wg sync.WaitGroup
errCh := make(chan error, 1)
Expand Down Expand Up @@ -682,6 +684,7 @@ func (c *Ring) ForEachShard(
}

func (c *Ring) cmdsInfo(ctx context.Context) (map[string]*CommandInfo, error) {
// note: `c.List()` return a shadow copy of `[]*ringShard`.
shards := c.sharding.List()
var firstErr error
for _, shard := range shards {
Expand Down Expand Up @@ -810,7 +813,7 @@ func (c *Ring) Watch(ctx context.Context, fn func(*Tx) error, keys ...string) er

for _, key := range keys {
if key != "" {
shard, err := c.sharding.GetByKey(hashtag.Key(key))
shard, err := c.sharding.GetByKey(key)
if err != nil {
return err
}
Expand Down
Loading