Build a new validator every time a DTO is constructed - is this performant?

A nice approach for validation I’ve seen recently is to make DTOs validate themselves inside their constructors so it is impossible to construct an invalid DTO. See example below.

To do the above requires every instance of a DTO to build itself a new instance of a validator on construction. For a typical webapp such DTOs could be of course be built 100s of times a second. Is building this many instances of validators recommended / performant? Is the factory effectively passing the same instance every time in any case so it doesn’t matter how many times it is called?

Thanks for any help with this :slight_smile:

Instantiating Validator instances is cheap (it will of course allocate more things than if you didn’t but it’s cheap). What you really need to avoid is building a new ValidatorFactory each time because that is expensive.

1 Like

Thanks so much! Might give that approach a try :slight_smile:

Although to be fair the solution given in the linked example does build a new ValidatorFactory every time a SelfValidating DTO is constructed - and so from the answer provided above this is expensive and so to be avoided.