]> Cypherpunks repositories - gostls13.git/commitdiff
math/big: minor performance tuning
authorRobert Griesemer <gri@golang.org>
Thu, 12 Jul 2012 21:12:50 +0000 (14:12 -0700)
committerRobert Griesemer <gri@golang.org>
Thu, 12 Jul 2012 21:12:50 +0000 (14:12 -0700)
Reuse temporary slice to avoid extra allocations
(originally done correctly by remyoudompheng@gmail.com
in https://golang.org/cl/6345075/).

benchmark           old ns/op    new ns/op    delta
BenchmarkHilbert      6252790      6262304   +0.15%
BenchmarkMul         45827438     45301002   -1.15%

R=r
CC=golang-dev
https://golang.org/cl/6346097

src/pkg/math/big/nat.go
src/pkg/math/big/nat_test.go

index 43d53d17a6e1bf01bab10f0613d72df706cf2c70..04f5dfd8babf82c17adb9192ef59dd2768f1a651 100644 (file)
@@ -438,8 +438,9 @@ func (z nat) mul(x, y nat) nat {
 
                // add x0*y1*b
                x0 := x0.norm()
-               y1 := y[k:] // y1 is normalized because y is
-               addAt(z, t.mul(x0, y1), k)
+               y1 := y[k:]       // y1 is normalized because y is
+               t = t.mul(x0, y1) // update t so we don't lose t's underlying array
+               addAt(z, t, k)
 
                // add xi*y0<<i, xi*y1*b<<(i+k)
                y0 := y0.norm()
@@ -449,8 +450,10 @@ func (z nat) mul(x, y nat) nat {
                                xi = xi[:k]
                        }
                        xi = xi.norm()
-                       addAt(z, t.mul(xi, y0), i)
-                       addAt(z, t.mul(xi, y1), i+k)
+                       t = t.mul(xi, y0)
+                       addAt(z, t, i)
+                       t = t.mul(xi, y1)
+                       addAt(z, t, i+k)
                }
        }
 
@@ -1232,7 +1235,7 @@ func (z nat) random(rand *rand.Rand, limit nat, n int) nat {
 // reuses the storage of z if possible.
 func (z nat) expNN(x, y, m nat) nat {
        if alias(z, x) || alias(z, y) {
-               // We cannot allow in place modification of x or y.
+               // We cannot allow in-place modification of x or y.
                z = nil
        }
 
index e4ea1ca441f7f589e9e0a90bb8bd551de041c391..f0c1ace73f2459cbeb288d504b051f7eff36cc5e 100644 (file)
@@ -179,7 +179,7 @@ func allocBytes(f func()) uint64 {
 
 // TestMulUnbalanced tests that multiplying numbers of different lengths
 // does not cause deep recursion and in turn allocate too much memory.
-// test case for issue 3807
+// Test case for issue 3807.
 func TestMulUnbalanced(t *testing.T) {
        x := rndNat(50000)
        y := rndNat(40)
@@ -201,7 +201,7 @@ func rndNat(n int) nat {
        for i := 0; i < n; i++ {
                x[i] = Word(rnd.Int63()<<1 + rnd.Int63n(2))
        }
-       return x
+       return x.norm()
 }
 
 func BenchmarkMul(b *testing.B) {