Link to home
Start Free TrialLog in
Avatar of mag062397
mag062397

asked on

Why is myList.isSelected(i) so slow? Is there a faster way?

Does anyone know how to speed up the following code?

len = myList.countItems();
for(i=0; i < len; i++) {
  if (myList.isSelected(i)) {
    // ... do something
  }
}

The time lag seems to be on checking to see if an item is selected or not.
Whether or not the item is selected in the list doesn't change the lag.

It takes about 1 sec per item.  For example, my list has 300 items and the
above code takes about 5 minutes to complete.

Thanks.
Avatar of msmolyak
msmolyak

What does isSelected() method do? If it's a short method which it should be then it should take much less than 1 sec to execute. Why don't you print the timestamp to figure out how much isSelected takes vs. the if blok itself.
The very first thing I'd do is get rid of len

for(int i = 0; i < myList.countItems(); i++)
{    if(myList.isSelected(i))
     {    //do stuff
     }
}

of course this is not a huge deal, unless this piece of code gets called a lot.
Avatar of mag062397

ASKER

Comment for msmolyak:

isSelected is a method in the java.awt.List class.

It determines whether an item in the list is selected or not.

The following code takes basiclly no time at all:

len = myList.countItems();
for(i=0; i < len; i++) {
  if (i==10) {
    System.out.println("Hello");
  }
}

So, I don't think it is the if statement.
-----------------------------------------------------------------------
Comment for webster

The len is there to speed things up.  It is my understanding the a function call takes longer than resolving the value of a variable.
My mistake. I must have been brain dead when I looked at that.
One solution I came up with is to use getMultipleSelections.

This ran much much faster.  It took 2 seconds to loop through 300 items.

However, I still wonder why isSelected runs so slowly.
????
ASKER CERTIFIED SOLUTION
Avatar of rembo
rembo

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial