From cc72aa92d93632ca0af0350c2f09847312433fba Mon Sep 17 00:00:00 2001 From: ionutboangiu Date: Wed, 27 Mar 2024 14:08:04 +0200 Subject: [PATCH] Slightly optimize debit for balances with non-nil Factor Factor will be computed only once at the start of the function, instead of doing it on every Increments iteration. 'amount' variable will be updated and rounded only when the computed balances factor is different from its default value (1). --- engine/balances.go | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/engine/balances.go b/engine/balances.go index 1978236c5..685d7baca 100644 --- a/engine/balances.go +++ b/engine/balances.go @@ -786,6 +786,9 @@ func (bc Balances) SaveDirtyBalances(acc *Account, initBal map[string]float64) { type ValueFactors map[string]float64 func (f ValueFactors) GetValue(category string) float64 { + if f == nil { + return 1.0 + } if value, ok := f[category]; ok { return value } @@ -859,6 +862,11 @@ func (b *Balance) debit(cd *CallDescriptor, ub *Account, moneyBalances Balances, if !isUnitBal { tor = utils.MetaMonetary } + + // Compute the balance factor ahead of time. If the map is nil, or + // the factor is not found, it will default to 1. + bFactor := b.Factor.GetValue(cd.ExtraFields[utils.BalanceFactorID]) + if duration, err_ := utils.ParseZeroRatingSubject(tor, b.RatingSubject, config.CgrConfig().RalsCfg().BalanceRatingSubject, isUnitBal); err_ == nil { // we have *zero based units @@ -899,10 +907,8 @@ func (b *Balance) debit(cd *CallDescriptor, ub *Account, moneyBalances Balances, for incIndex, inc := range ts.Increments { //log.Printf("INCREMENET: %+v", inc) amount := float64(inc.Duration) - if b.Factors != nil { - amount = utils.Round( - amount*b.Factors.GetValue(cd.ExtraFields[utils.BalanceFactorID]), - globalRoundingDecimals, utils.MetaRoundingUp) + if bFactor != 1 { + amount = utils.Round(amount*bFactor, globalRoundingDecimals, utils.MetaRoundingUp) } if b.GetValue() >= amount { b.SubtractValue(amount) @@ -1044,10 +1050,8 @@ func (b *Balance) debit(cd *CallDescriptor, ub *Account, moneyBalances Balances, canDebitCost := b.GetValue() >= cost var moneyBal *Balance if isUnitBal { - if b.Factors != nil { - amount = utils.Round( - amount*b.Factors.GetValue(cd.ExtraFields[utils.BalanceFactorID]), - globalRoundingDecimals, utils.MetaRoundingUp) + if bFactor != 1 { + amount = utils.Round(amount*bFactor, globalRoundingDecimals, utils.MetaRoundingUp) } for _, mb := range moneyBalances { if mb.GetValue() >= cost {