Skip to content

Commit

Permalink
ecs: Use atomic increment in NewID instead of lock.
Browse files Browse the repository at this point in the history
Original issue reported by @EtienneBruines in EngoEngine/ecs#21

   u@x1 ~/D/g/s/g/m/e/ecs> benchcmp old.txt new.txt
   benchmark            old ns/op     new ns/op     delta
   BenchmarkNewID-4     27.0          10.6          -60.74%
  • Loading branch information
mewmew committed May 13, 2016
1 parent c81a642 commit 14bc276
Showing 1 changed file with 5 additions and 19 deletions.
24 changes: 5 additions & 19 deletions ecs/ecs.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,7 @@
package ecs

import (
"fmt"
"sync"
"sync/atomic"
"time"
)

Expand Down Expand Up @@ -87,23 +86,10 @@ type ID struct {
id uint64
}

// unique provides access to unique entity IDs, starting at 1.
var unique uint64

// NewID returns a new unique ID. It is safe for concurrent use.
func NewID() ID {
gen.Lock()
prev := gen.ID
gen.id++
if gen.id == 0 {
panic(fmt.Sprintf("entity ID overflow detected; new ID (%d) < previous ID (%d)", gen.id, prev))
}
gen.Unlock()
return gen.ID
}

// unique provides access to unique entity IDs.
type unique struct {
ID
sync.Mutex
return ID{id: atomic.AddUint64(&unique, 1)}
}

// gen generates unique entity IDs starting at 1.
var gen unique

0 comments on commit 14bc276

Please sign in to comment.