This commit is contained in:
DanB
2013-08-18 17:06:32 +02:00
2 changed files with 36 additions and 0 deletions

View File

@@ -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 {

View File

@@ -19,6 +19,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>
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"})
}
}