runtime: faster range on empty map
benchmark old ns/op new ns/op delta
BenchmarkMapIter 191 190 -0.52%
BenchmarkMapIterEmpty 22 4 -78.96%
R=golang-dev, minux.ma, dvyukov, iant, khr
CC=golang-dev
https://golang.org/cl/9637043
diff --git a/src/pkg/runtime/hashmap.c b/src/pkg/runtime/hashmap.c
index 892f0a1..959d6bc 100644
--- a/src/pkg/runtime/hashmap.c
+++ b/src/pkg/runtime/hashmap.c
@@ -1355,7 +1355,7 @@
void
runtime·mapiterinit(MapType *t, Hmap *h, struct hash_iter *it)
{
- if(h == nil) {
+ if(h == nil || h->count == 0) {
it->key = nil;
return;
}
diff --git a/src/pkg/runtime/mapspeed_test.go b/src/pkg/runtime/mapspeed_test.go
index a737c65..13b5762 100644
--- a/src/pkg/runtime/mapspeed_test.go
+++ b/src/pkg/runtime/mapspeed_test.go
@@ -233,3 +233,24 @@
_ = make(map[int]int)
}
}
+
+func BenchmarkMapIter(b *testing.B) {
+ m := make(map[int]bool)
+ for i := 0; i < 8; i++ {
+ m[i] = true
+ }
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ for _, _ = range m {
+ }
+ }
+}
+
+func BenchmarkMapIterEmpty(b *testing.B) {
+ m := make(map[int]bool)
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ for _, _ = range m {
+ }
+ }
+}