Skip to content

Commit 7e7acaf

Browse files
committed
MST memory improvement
1 parent 35548d3 commit 7e7acaf

File tree

5 files changed

+34
-9
lines changed

5 files changed

+34
-9
lines changed

mst.go

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -19,16 +19,18 @@ func MST(g Iterator) (parent []int) {
1919

2020
// Prim's algorithm
2121
Q := newPrioQueue(cost)
22+
var v int
23+
do := func(w int, c int64) (skip bool) {
24+
if Q.Contains(w) && c < cost[w] {
25+
cost[w] = c
26+
Q.Fix(w)
27+
parent[w] = v
28+
}
29+
return
30+
}
2231
for Q.Len() > 0 {
23-
v := Q.Pop()
24-
g.Visit(v, func(w int, c int64) (skip bool) {
25-
if Q.Contains(w) && c < cost[w] {
26-
cost[w] = c
27-
Q.Fix(w)
28-
parent[w] = v
29-
}
30-
return
31-
})
32+
v = Q.Pop()
33+
g.Visit(v, do)
3234
}
3335
return
3436
}

mst_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ func TestMST(t *testing.T) {
3434

3535
func BenchmarkMST(b *testing.B) {
3636
n := 1000
37+
b.ReportAllocs()
3738
b.StopTimer()
3839
g := New(n)
3940
for i := 0; i < 2*n; i++ {

testdata/bench_after/MST

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
goos: linux
2+
goarch: amd64
3+
pkg: github.com/rschio/graph
4+
cpu: Intel(R) Core(TM) i5-8350U CPU @ 1.70GHz
5+
BenchmarkMST-8 5379 189717 ns/op 32951 B/op 8 allocs/op
6+
PASS
7+
ok github.com/rschio/graph 1.048s

testdata/bench_before/MST

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
goos: linux
2+
goarch: amd64
3+
pkg: github.com/rschio/graph
4+
cpu: Intel(R) Core(TM) i5-8350U CPU @ 1.70GHz
5+
BenchmarkMST-8 4191 249128 ns/op 96883 B/op 1006 allocs/op
6+
PASS
7+
ok github.com/rschio/graph 1.078s

testdata/bench_results/MST

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
name old time/op new time/op delta
2+
MST-8 249µs ± 0% 190µs ± 0% -23.85%
3+
4+
name old alloc/op new alloc/op delta
5+
MST-8 96.9kB ± 0% 33.0kB ± 0% -65.99%
6+
7+
name old allocs/op new allocs/op delta
8+
MST-8 1.01k ± 0% 0.01k ± 0% -99.20%

0 commit comments

Comments
 (0)