Reverting to slicebased memdb after checking benchmark.

This commit is contained in:
claudemiro
2016-09-01 23:42:55 -03:00
parent 8fb96f3cbf
commit 5c9528bce4
2 changed files with 28 additions and 27 deletions
+15 -27
View File
@@ -18,50 +18,38 @@ type db interface {
AddApp(*app) error AddApp(*app) error
} }
// memdb is an in memory implementation of db interface
type memdb struct { type memdb struct {
IDMutex sync.Mutex sync.Mutex
KeyMutex sync.Mutex Apps []*app
AppsByAppID map[string]*app
AppsByKey map[string]*app
} }
func newMemdb() *memdb { func newMemdb() db {
return &memdb{ return &memdb{}
AppsByAppID: make(map[string]*app),
AppsByKey: make(map[string]*app),
}
} }
func (db *memdb) AddApp(a *app) error { func (db *memdb) AddApp(a *app) error {
db.IDMutex.Lock() db.Lock()
db.AppsByAppID[a.AppID] = a db.Apps = append(db.Apps, a)
db.IDMutex.Unlock() db.Unlock()
db.KeyMutex.Lock()
db.AppsByKey[a.Key] = a
db.KeyMutex.Unlock()
return nil return nil
} }
// GetAppByAppID returns an App with by appID // GetAppByAppID returns an App with by appID
func (db *memdb) GetAppByAppID(appID string) (*app, error) { func (db *memdb) GetAppByAppID(appID string) (*app, error) {
db.IDMutex.Lock() for _, a := range db.Apps {
a, ok := db.AppsByAppID[appID] if a.AppID == appID {
db.IDMutex.Unlock() return a, nil
if ok { }
return a, nil
} }
return nil, errors.New("App not found") return nil, errors.New("App not found")
} }
// GetAppByKey returns an App with by key // GetAppByKey returns an App with by key
func (db *memdb) GetAppByKey(key string) (*app, error) { func (db *memdb) GetAppByKey(key string) (*app, error) {
db.KeyMutex.Lock() for _, a := range db.Apps {
a, ok := db.AppsByKey[key] if a.Key == key {
db.KeyMutex.Unlock() return a, nil
if ok { }
return a, nil
} }
return nil, errors.New("App not found") return nil, errors.New("App not found")
} }
+13
View File
@@ -6,6 +6,19 @@ package ipe
import "testing" import "testing"
func Benchmark_memdb_GetAppByAppID(b *testing.B) {
db := newMemdb()
db.AddApp(&app{AppID: "123456", Name: "Example"})
db.AddApp(&app{AppID: "654321", Name: "Example2"})
db.AddApp(&app{AppID: "678901", Name: "Example3"})
b.ResetTimer()
for i := 0; i < b.N; i++ {
db.GetAppByAppID("123456")
}
}
func Test_db_GetAppByAppID(t *testing.T) { func Test_db_GetAppByAppID(t *testing.T) {
app := &app{AppID: "123456", Name: "Example"} app := &app{AppID: "123456", Name: "Example"}