jQuery in Action, 2nd edition*
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
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.
 
Don't get me started about those stupid light bulbs.
 
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)