File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Performance and the fly likes casting reductions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Performance
Bookmark "casting reductions" Watch "casting reductions" New topic

casting reductions

Marilyn de Queiroz

Joined: Jul 22, 2000
Posts: 9058
Let's push on and try eliminating the unnecessary String casts. This is done by simply holding the first casted object in a variable of the appropriate type. For example:
for(int i = 0; i < max; i++)
if( ( ((String) collection.get(i)).indexOf("ie") != -1 )
| | ( ((String) collection.get(i)).indexOf("xy") != -1 )
| | ( ((String) collection.get(i)).indexOf("pq") != -1 ) )
String s;
for(int i = 0; i < max; i++)
if( ( (s = (String) collection.get(i)).indexOf("ie") != -1 )
| | ( s.indexOf("xy") != -1 )
| | ( s.indexOf("pq") != -1 ) )
How do you know that the difference in performance is only due to the reduction in casting? Aren't you also getting rid of a method call at the same time?

"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Jack Shirazi
Ranch Hand

Joined: Oct 26, 2000
Posts: 96
You are completely right. Until you just pointed it out I didn't notice that I had combined the two optimizations. This is quite common - it's too easy to combine optimizations without testing each separately.
Both optimizations should have independently worked to have slightly speeded up the test.
I agree. Here's the link:
subject: casting reductions
It's not a secret anymore!