]> Cypherpunks repositories - gostls13.git/commitdiff
math/big: avoid some allocation in Exp
authorAdam Langley <agl@golang.org>
Mon, 1 Oct 2012 21:31:35 +0000 (17:31 -0400)
committerAdam Langley <agl@golang.org>
Mon, 1 Oct 2012 21:31:35 +0000 (17:31 -0400)
benchmark                        old ns/op    new ns/op    delta
BenchmarkRSA1024Decrypt             745686       644964  -13.51%
BenchmarkRSA2048Decrypt            5517318      5049200   -8.48%
Benchmark3PrimeRSA2048Decrypt      3767386      3288048  -12.72%

R=gri
CC=gobot, golang-dev
https://golang.org/cl/6566043

src/pkg/math/big/nat.go

index 85b9acc0f5113f8ba3998fc9c0f01f460242091c..2d5a5c9587d6878d6d8d4b65124fb0a572843d3b 100644 (file)
@@ -1264,15 +1264,21 @@ func (z nat) expNN(x, y, m nat) nat {
        // we also multiply by x, thus adding one to the power.
 
        w := _W - int(shift)
+       // zz and r are used to avoid allocating in mul and div as
+       // otherwise the arguments would alias.
+       var zz, r nat
        for j := 0; j < w; j++ {
-               z = z.mul(z, z)
+               zz = zz.mul(z, z)
+               zz, z = z, zz
 
                if v&mask != 0 {
-                       z = z.mul(z, x)
+                       zz = zz.mul(z, x)
+                       zz, z = z, zz
                }
 
                if m != nil {
-                       q, z = q.div(z, z, m)
+                       zz, r = zz.div(r, z, m)
+                       zz, r, q, z = q, z, zz, r
                }
 
                v <<= 1
@@ -1282,14 +1288,17 @@ func (z nat) expNN(x, y, m nat) nat {
                v = y[i]
 
                for j := 0; j < _W; j++ {
-                       z = z.mul(z, z)
+                       zz = zz.mul(z, z)
+                       zz, z = z, zz
 
                        if v&mask != 0 {
-                               z = z.mul(z, x)
+                               zz = zz.mul(z, x)
+                               zz, z = z, zz
                        }
 
                        if m != nil {
-                               q, z = q.div(z, z, m)
+                               zz, r = zz.div(r, z, m)
+                               zz, r, q, z = q, z, zz, r
                        }
 
                        v <<= 1