From b894ab823608f95affa1f9eaafda8a7ef53b4c42 Mon Sep 17 00:00:00 2001 From: Radu Ioan Fericean Date: Fri, 16 Aug 2013 13:46:19 +0300 Subject: [PATCH] faster history record search --- history/scribe.go | 15 +++++++++++++++ history/scribe_test.go | 21 +++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/history/scribe.go b/history/scribe.go index 6ec0fffa5..a1dd72aff 100644 --- a/history/scribe.go +++ b/history/scribe.go @@ -55,6 +55,21 @@ func (rs records) Sort() { } func (rs records) SetOrAdd(rec *Record) records { + //rs.Sort() + n := len(rs) + i := sort.Search(n, func(i int) bool { return rs[i].Key >= rec.Key }) + if i < n && rs[i].Key == rec.Key { + rs[i].Object = rec.Object + } else { + // i is the index where it would be inserted. + rs = append(rs, nil) + copy(rs[i+1:], rs[i:]) + rs[i] = rec + } + return rs +} + +func (rs records) SetOrAddOld(rec *Record) records { found := false for _, r := range rs { if r.Key == rec.Key { diff --git a/history/scribe_test.go b/history/scribe_test.go index 324a4770c..8f586dcf5 100644 --- a/history/scribe_test.go +++ b/history/scribe_test.go @@ -19,6 +19,7 @@ along with this program. If not, see package history import ( + "strconv" "testing" ) @@ -37,3 +38,23 @@ func TestHistoryAdd(t *testing.T) { t.Error("error setting new value: ", rs) } } + +func BenchmarkSetOrAdd(b *testing.B) { + var rs records + for i := 0; i < 1000; i++ { + rs = rs.SetOrAdd(&Record{strconv.Itoa(i), strconv.Itoa(i)}) + } + for i := 0; i < b.N; i++ { + rs.SetOrAdd(&Record{"400", "test"}) + } +} + +func BenchmarkSetOrAddOld(b *testing.B) { + var rs records + for i := 0; i < 1000; i++ { + rs = rs.SetOrAddOld(&Record{strconv.Itoa(i), strconv.Itoa(i)}) + } + for i := 0; i < b.N; i++ { + rs.SetOrAddOld(&Record{"400", "test"}) + } +}