Skip to content

Commit

Permalink
Improve SelectVariant performance (#187)
Browse files Browse the repository at this point in the history
* Improve SelectVariant performance

A three changes were made to improve performance:

- totalWeight was not needed, per the docs this will always be 100%.
This removes the Sum call which loops over the list of variants.
- The FirstOrDefault call was removed, this allows for us to loop over
the list of variants only once.
- We check if there are any overrides before calling Any.

* Fix failing tests

* Add back weight
  • Loading branch information
nathanmascitelli authored Jan 3, 2024
1 parent e86849d commit ee158d1
Showing 1 changed file with 13 additions and 16 deletions.
29 changes: 13 additions & 16 deletions src/Unleash/Variants/VariantUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,33 +14,35 @@ public static Variant SelectVariant(string groupId, UnleashContext context, List
{
var totalWeight = variantDefinitions.Sum(v => v.Weight);

if (totalWeight == 0) {
return null;
}

var variantOverride = GetOverride(variantDefinitions, context);
if (variantOverride != null)
if (totalWeight == 0)
{
return variantOverride.ToVariant();
return null;
}

var stickiness = variantDefinitions[0].Stickiness ?? "default";
var stickiness = variantDefinitions.FirstOrDefault()?.Stickiness ?? "default";
var target = StrategyUtils.GetNormalizedNumber(GetIdentifier(context, stickiness), groupId, VARIANT_NORMALIZATION_SEED, totalWeight);

var counter = 0;
Variant result = null;
foreach (var variantDefinition in variantDefinitions)
{
if (variantDefinition.Weight != 0)
{
if (variantDefinition.Overrides.Count > 0 && variantDefinition.Overrides.Any(OverrideMatchesContext(context)))
{
result = variantDefinition.ToVariant();
break;
}

counter += variantDefinition.Weight;
if (counter >= target)
if (counter >= target && result == null)
{
return variantDefinition.ToVariant();
result = variantDefinition.ToVariant();
}
}
}

return null;
return result;
}

public static Variant SelectVariant(FeatureToggle feature, UnleashContext context, Variant defaultVariant = null)
Expand All @@ -54,11 +56,6 @@ public static Variant SelectVariant(FeatureToggle feature, UnleashContext contex

}

private static VariantDefinition GetOverride(List<VariantDefinition> variants, UnleashContext context)
{
return variants.FirstOrDefault(v => v.Overrides.Any(OverrideMatchesContext(context)));
}

private static Func<VariantOverride, bool> OverrideMatchesContext(UnleashContext context)
{
return (variantOverride) =>
Expand Down

0 comments on commit ee158d1

Please sign in to comment.