Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

impact of javax.servlet.Filter on performance?

I would like to know if any hard data exist on the cost of using a Filter ? For instance, between using heritage on servlet for sharing a behavior, or using a filter ?

Thanks,

Antoine

like image 961
Antoine Claval Avatar asked Jan 13 '11 10:01

Antoine Claval


2 Answers

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.

like image 104
duffymo Avatar answered Oct 20 '22 09:10

duffymo


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.

like image 37
Thilo Avatar answered Oct 20 '22 07:10

Thilo