this repo has no description
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

internal/core/convert: avoid an allocation for "small" big.Int values

If we can represent the integer as an int64,
the conversion from math/big.Int to apd.Decimal does not need to go
through an extra apd.BigInt step, which also allocates.

│ old │ new │
│ B/op │ B/op vs base │
VetInventory 4.627Gi ± ∞ ¹ 4.618Gi ± ∞ ¹ -0.20% (p=1.000 n=1)

│ old │ new │
│ allocs/op │ allocs/op vs base │
VetInventory 49.61M ± ∞ ¹ 49.29M ± ∞ ¹ -0.64% (p=1.000 n=1)

Signed-off-by: Daniel Martí <mvdan@mvdan.cc>
Change-Id: I08fcf54ef76ff4d16b531b278cfce79a1ef368ec
Reviewed-on: https://review.gerrithub.io/c/cue-lang/cue/+/1229430
Unity-Result: CUE porcuepine <cue.porcuepine@gmail.com>
TryBot-Result: CUEcueckoo <cueckoo@cuelang.org>
Reviewed-by: Matthew Sackman <matthew@cue.works>

+15 -5
+15 -5
internal/core/convert/go.go
··· 224 224 return &adt.Num{ 225 225 Src: src, 226 226 K: adt.IntKind, 227 - X: *apd.NewWithBigInt(new(apd.BigInt).SetMathBigInt(v), 0), 227 + X: fromGoBigInt(v), 228 228 } 229 229 230 230 case bigRat: 231 231 v, _ := val.Interface().(*big.Rat) // TODO(go1.25): use reflect.TypeAssert 232 232 // should we represent this as a binary operation? 233 233 n := &adt.Num{Src: src, K: adt.IntKind} 234 - if _, err := internal.BaseContext.Quo(&n.X, 235 - apd.NewWithBigInt(new(apd.BigInt).SetMathBigInt(v.Num()), 0), 236 - apd.NewWithBigInt(new(apd.BigInt).SetMathBigInt(v.Denom()), 0), 237 - ); err != nil { 234 + num := fromGoBigInt(v.Num()) 235 + denom := fromGoBigInt(v.Denom()) 236 + if _, err := internal.BaseContext.Quo(&n.X, &num, &denom); err != nil { 238 237 return ctx.AddErrf("could not convert *big.Rat: %v", err) 239 238 } 240 239 if !v.IsInt() { ··· 509 508 return v 510 509 } 511 510 return nil 511 + } 512 + 513 + func fromGoBigInt(x *big.Int) apd.Decimal { 514 + // Integers fitting in 64 bits is rather common. 515 + // In that case, avoid the conversion to [apd.BigInt], which also allocates. 516 + if x.IsInt64() { 517 + var dec apd.Decimal 518 + dec.SetInt64(x.Int64()) 519 + return dec 520 + } 521 + return *apd.NewWithBigInt(new(apd.BigInt).SetMathBigInt(x), 0) 512 522 } 513 523 514 524 func ensureArcVertex(ctx *adt.OpContext, x adt.Value, l adt.Feature) *adt.Vertex {