简体   繁体   中英

JAVA - Speed up the code

I want to speed up the my code. Quick status information:

  • There is more than one list ( String ) like _list1 , _list2 , _list3 .

  • I try to find a word ( String ) in these lists.

  • If I find a word, I will use index of the word on the list.

Here is my code:

private static int foundIndex (String s) 
{
    if (_list1.contains(s)) {
        return _list1.indexOf(s);
    } else if (_list2.contains(s)) {
        return _list2.indexOf(s);
    } else if (_list3.contains(s)) {
        return _list3.indexOf(s);
    } else if (_list4.contains(s)) {
        return _list4.indexOf(s);
    }
...
...
...
...
    } else if (_list100.contains(s)) {
        return _list100.indexOf(s);
    }
    return -1;
}

How can I speed up the my code?

A couple simple optimizations comes to mind:

1.replace the if (contains) then indexOf pattern with if (i = indexOf(s) >= 0) return i

2.add lookup data structure like a Map<String,Integer> and either use it instead of the lists or in addition to them by updating it whenever you add or change a list

Add all your lists ( String ) in a List<String> and iterate on it :

private static int foundIndex (String s) {
   for (String currentList : lists){
       int indexOf = currentList.indexOf(s);
       if (indexOf != -1) {
          return indexOf;
       }
    }
    return -1;
}

I changed the algorithm of my code to your suggestions. I was use list to much before, now I changed it. I use 2D String array. But code performance was 157% decrease.

New Code :

private static String[][] _lists = new String[200][100];

private static int foundIndex (String s) {
for (int i = 0; i < 200; i++) {
        for (int j = 0; j < 100; j++) {
            if (_lists[i][j].equals(s) == true) {
                return j;
            }
        }
    }
    return -1;
}

That's where the problem starts.

If the code I'm looking for is "_list[180][?]", it's hard to find it.

How can I speed up the my code?

Thank you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM