views:

342

answers:

3

I've a Servlet filter which performs the following type cast:

HttpServletRequest httpRequest = (HttpServletRequest) req;

At present my filter is responsible for two tasks that would be better separated into two filters. If I'd split the logic into two filters I'd need two casts.

What is the performance impact of such a cast? Is it worth to accept this performance degradation for a better architecture?

+2  A: 

The cast has almost no performance impact. (Edited, thanks to commentors)

As long as you have no real performance problem, always go for better architecture.

Peter Lang
Your first statemet is absolutely wrong. A cast in Java involves runtime work - at the very least the JVM has to check if the object is in fact of the required type so that it can throw a ClassCastException when it's not.
Michael Borgwardt
Casts in Java can be optimized away in special cases by the compiler - but in most cases, such as this, it does involve runtime work. So, there is a performance impact, even if not especially relevant in this case.
Nakedible
+8  A: 

What is the performance impact of such a cast?

As compared to handling a HTTP request? Absolutely none. If you were doing it in a deeply nested loop that does little else it might matter, but not when it's done once for a task that involves things that are literally millions of times more work (like doing DB requests or accessing the harddisk).

Michael Borgwardt
+3  A: 

Performance impact will be negligible (compared to the total work done). Java does a lot of casting, like in the collection framework, hence the engineers already optimized it well. An additional casting won't change much, besides, readability (maintainability?) is more important.

RichN
Do you have a link and/or reference for that, please?
DerMike
@DerMike I forgot, sorry. In the meantime, feel free to downvote.
RichN