简体   繁体   English

验证类应该是静态类吗?

[英]Should validation classes be static classes?

I m working on a system which get thousands of requests per second, and essentially one of the tasks we are trying to avoid is to create unnecessary/extra objects . 我正在研究一个每秒可以获得数千个请求的系统,基本上我们要避免的一个任务是创建不必要的/额外的对象

We need to validate incoming request for 6 request items per se. 我们需要验证6个请求项本身的传入请求。

I m thinking of creating a class per each item validation. 我想为每个项目验证创建一个类。

However, I m trying to justify if i should use static validation classes vs object with instances that contains HttpRequest as the instance field. 但是,我试图证明我是否应该使用静态验证类vs对象与包含HttpRequest的实例作为实例字段。

should i use static classes or objects? 我应该使用静态类或对象吗? what would you do? 你会怎么做?

Essentially, what I m doing is injecting List<IValidator> validators to request handler and iterating over it. 本质上,我正在做的是注入List<IValidator> validators来请求处理程序并迭代它。 but not sure if i should have an instance vs static classes. 但不确定我是否应该有一个实例与静态类。

Have you actually measured the impact creating new Validator instances has on memory versus re-using static methods? 您是否真的测量过创建新Validator实例对内存的影响与重新使用静态方法的影响? The cost of using a short-lived object is very, very small. 使用短寿命对象的成本非常非常小。 You should measure what the difference between the two approaches is and if there is no measurable difference, use the one where the code is cleaner and easier to understand. 您应该测量两种方法之间的差异,如果没有可测量的差异,请使用代码更清晰,更易于理解的方法。

In cases like this it always makes sense to measure the difference instead of just assuming one versus the other is better. 在这种情况下,衡量差异总是有意义的,而不是仅假设一个与另一个相比更好。

In multithreaded environments, using static classes / methods always open concurrency pitfalls. 在多线程环境中,使用静态类/方法始终会打开并发陷阱。 Since the creation and collection of short lived objects is cheap, it is often better to create short lived objects than running into cuncurrency issues and extra synchronization, which is expensive. 由于短期对象的创建和收集很便宜,因此创建短期对象通常比运行到cuncurrency问题和额外同步(这是昂贵的)更好。

Struts switched from static request handlers to instance-based request handlers for similar reasons. 出于类似的原因, Struts从静态请求处理程序切换到基于实例的请求处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM