mirror of
https://github.com/lightninglabs/lightning-terminal.git
synced 2026-08-13 12:33:36 +02:00
firewall: optimize CryptoRandIntn with sync.Pool
Utilize a sync.Pool for *big.Int instances in CryptoRandIntn to avoid frequent heap allocations. This significantly reduces garbage collection pressure when randomizing timestamps, amounts, and fees inside loops (e.g. iterating over forwarding history responses).
This commit is contained in:
parent
6d89f07037
commit
cf7e53842a
1 changed files with 15 additions and 1 deletions
|
|
@ -11,6 +11,7 @@ import (
|
||||||
"math/big"
|
"math/big"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/btcsuite/btcd/chaincfg/chainhash"
|
"github.com/btcsuite/btcd/chaincfg/chainhash"
|
||||||
|
|
@ -1857,13 +1858,26 @@ func hideBool(randIntn func(n int64) (int64, error)) (bool, error) {
|
||||||
return random >= 1, nil
|
return random >= 1, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// bigIntPool is a pool of *big.Int values to avoid frequent heap allocations in
|
||||||
|
// CryptoRandIntn.
|
||||||
|
var bigIntPool = sync.Pool{
|
||||||
|
New: func() any {
|
||||||
|
return new(big.Int)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
// CryptoRandIntn generates a random number between [0, n).
|
// CryptoRandIntn generates a random number between [0, n).
|
||||||
func CryptoRandIntn(n int64) (int64, error) {
|
func CryptoRandIntn(n int64) (int64, error) {
|
||||||
if n == 0 {
|
if n == 0 {
|
||||||
return 0, nil
|
return 0, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
randBig, err := rand.Int(rand.Reader, big.NewInt(n))
|
nBig := bigIntPool.Get().(*big.Int)
|
||||||
|
defer bigIntPool.Put(nBig)
|
||||||
|
|
||||||
|
nBig.SetInt64(n)
|
||||||
|
|
||||||
|
randBig, err := rand.Int(rand.Reader, nBig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue