Elena T
Elena T

Reputation: 69

Validation with annotations is slow

Why is the spring validation slower than own validation? I'd like to refrain from writing my own validators.

Having 20,000 items(none causing a validation excepton) in the cart and calling both rest endpoints we get in these times: /test/spring -> 62.145 ms /test/own -> 11.35 ms

Both endpoints run 200 times. The time resulted is an average time. A cart with a 20.000 items is of course not realistic, this is also not the point here.

    @RequestMapping(path = "/spring", method = RequestMethod.POST)
    public ResponseEntity<Object> postSpringValidation(@RequestBody **@Valid** Cart cart) {
        return new ResponseEntity<>(HttpStatus.CREATED);
    }


@RequestMapping(path = "/own", method = RequestMethod.POST)
    public ResponseEntity<Object> postOwnValidation(@RequestBody Cart cart) {
        if (!cart.isValidData()) {
            throw new InvalidParameterException("invalid data");
        }

        return new ResponseEntity<>(HttpStatus.CREATED);
    }

public class Cart {
    @NotNull
    private String id;

    @Valid
    @NotNull
    private List<Item> items;

    public boolean isValidData() {
        if (id == null)
            return false;

        for (Item item : items) {
            if (!item.isValidData()) {
                return false;
            }
        }

        return true;
    }
}

public class Item {
    @NotNull
    private String id;

    public boolean isValidData() {
        if (id == null)
            return false;

        return true;
    }
}

Upvotes: 4

Views: 5196

Answers (1)

hovanessyan
hovanessyan

Reputation: 31483

Spring Validation implements JSR-303/JSR-349.

The validation routine part explains what happens when the validation triggers. You have to think about what is involved in the works for a global validation framework.

  • You need to have some way to detect which classes have declared constraints, and which not

  • You need a way to differentiate between constructor/method/field constraints

  • You need to implement some sort of object graph to validate deeply nested structures

This is all covered in this part of the documentation.

Operating this whole validation infrastructure is expected to be heavier, than having one in-line method in your class that does the validation.

It's better to have an uniformed way of applying validation than having custom implementation. Custom implementations are error prone and hard to maintain.

The performance overhead of any validation framework should be negligible in comparison with custom validation.

You have created unrealistic case for your product. I doubt you have someone buying 20K items at once. Even if you allow it, the client will not be able to pay. Most payment providers and banks will flag this transaction as ridiculous and deny it.

Upvotes: 6

Related Questions