This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Performance
Bookmark "casting reductions" Watch "casting reductions" New topic
Author

casting reductions

Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9044
    
  10
<pre>
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 ) )
becomes
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 ) )
</pre>
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?
Marilyn

JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Jack Shirazi
Author
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.
 
 
subject: casting reductions
 
Similar Threads
nextindex of
how ro get a string from a string
String Operations
how to search for string in file
How to find a word in a text file? (2)