views:

92

answers:

3

I have two questions. The first is do Filters add a lot of overhead to request. We have a filter and it is set to run on the URL pattern /*. This means it also runs on all the image request. I think that this is not good for performance, but my co-workers think that it doesn't matter if the filter runs 5 or 6 times per request because the filter only has a couple of if statements.

Is there a way to have the filter run once per request, ignoring the image request.

Thanks Doug

+2  A: 

Measuring is knowing. If well-written, I'd say, it's negligible. But if it's for example grabbing the session regardless of it's been created (and thus there's a chance that it will unnecessarily be created), then it may have a noticeable impact on performance and/or memory usage because creation of sessions isn't per-se cheap and sessions are stored in sever's memory for a longer term than the requests.

You may want to replace the url-pattern of /* by *.jsp or to move the restricted pages to a specific folder, e.g. /secured, /private, /pages, etc and alter the url-pattern accordingly to /secured/*, /private/*, /pages/*, etc and put all the static content in a different place, e.g. /static. This way the filter won't be invoked for static content anymore.

BalusC
Agreed about measuring. We're treading very near premature optimization with this question.
Ian McLaird
A: 

It almost never useful to speculate about the performance implications of code without first profiling it. Unless the code being proposed in the filters is doing some operations you know to be slow then measure first before optimising.

Remember even though when you are writing a servlet it may seem like the only thing that happens is the code in your doGet() or doPost() methods a lot of other things happen before your servlet/filter code gets invoked. The servlet container processes the HTTP request bundles it up in Java objects and does all sorts of other processing before it hands over to your code.

If your servlet filters really are only a couple of if statements operating on data that is cheap to get (such as the request itself), it is unlikely this is going to be an issue for you.

Tendayi Mawushe
+2  A: 

First, I agree with the Profile-first approach.

Second, as far as I know it depends, web-server use the same technique to invoke a specific servelt(/JSP) as they use for filters.

In case the filter is filtering a static resource(e.g. jpg file), it's a bit of a waste, In case the filter is filtering a dynamic resource (e.g. Servlet) it's negligible.. (Most of the Java web frameworks like struts and Jboss-seam are using filters heavily..)

MrOhad