- Frugal Cafe
- Posts
- FC62: Peel the FluentValidation Onion
FC62: Peel the FluentValidation Onion
It looks like lots of people are actually using it
From complete analysis sequence analysis of FludentValidation of a single Customer class (FC61: Complete allocation sequence (beehiiv.com)), we know there are 44 allocations, 2,172 bytes. Now let’s peel the onion.
From the data, there seems to be 5 sets of allocations related to Lazy usage, one for each property value in the validator. Let’s get rid of this one first:
We’re replacing lazy accessor with a Boolean flag and a property value local variable. Here is the new allocation sequence:
Now it’s down to 29 object allocations, 1,532 bytes.
There are 5 Func delegates left, again one for each property. Get’s get rid of them too:
This could be written as:
Now the delegate is properly reused, getting rid of 5 allocations.
There are two CharEnumerator allocated from here:
This is very inefficient code, let’s change it to:
Notice Array is not needed because it implements ICollection interface. Here is the source of another enumerator allocation:
We can get rid of enumerator allocation using for loop:
The last a few allocations look strange. We have HashSet, Dictionary, then string array. Here is the source of the confusion:
This can be replaced by:
Now we’re down to just 15 allocations, 772 bytes (64% reduction):
Notice there are two PropertyChain objects, each with a List with a string array inside. Only a single PropertyChain is needed, it can be fused with List, and the string array does not need to be allocated. This:
Can be changed to:
Now we down to just 10 allocations, 604 bytes:
More optimizations are still possible, but let’s check with the repo owner first. Eventually, we can reduce it to just single allocation for the customer, all other allocations can be reused.