impact of javax.servlet.Filter on performance?
I would like to know if any hard data exist on the cost of using a Filter ? Fo开发者_Go百科r instance, between using heritage on servlet for sharing a behavior, or using a filter ?
Thanks,
Antoine
I'll be surprised if someone can post hard data. And even if they do, it most likely won't be pertinent to you, because the numbers will depend on what's being done in the filter. It's also likely to fall into the premature optimization category - it isn't likely to matter unless you really screw something up badly.
I'll assume that "heritage" means "inheritance" and say that filters are a far better solution. You have the option of turning them off and on in configuration.
Filters are decorators or aspects for HTTP requests. Since those are well-respected, tried-and-true patterns, why would they not be useful and safe for use by servlets?
I'd say your concerns are overblown.
With that said, I would not recommend building such a long, complex filter chain that performance does become an issue. You could end up with a problem if you do compression, logging, performance metrics, etc. and end up with a chain of a dozen filters.
Nothing measurable, totally dwarfed by the actual work you do in the Filter. There is not even a new instance of the Filter created every time, just like Servlets they are shared.
The big advantage over inheritance is the ability to configure and compose at runtime (a parent class is compiled in, and there can be only one).
One thing to consider is that a Filter can only wrap a request: it can add code before and after (or instead). And after the Servlet has run, the response may already have been committed. It cannot inject code into the middle of request processing, which a properly defined callback into a parent class (or some other technique at the Servlet end of things) could do. This means that a Filter may not be appropriate for certain tasks.
精彩评论