cat96 cat96 - 5 months ago 10
Java Question

Java accessing elements in an arraylist slower over time

I have some code, and I noticed that the progress of iterating through an ArrayList became drastically slower over time. The code that seems to be causing the problem is as below:

public boolean isWordOfficial(String word){
return this.wordList.get(this.stringWordList.indexOf(word)).isWordOfficial();
}


Is there something about this code I don't know in terms of accessing the two arraylists?

Answer

I don't exactly why, or by how much, your ArrayList performance is becoming too slow, but from a quick glance at your use case, you are doing the following operations:

  • given a String word, look it up in stringWordList, and return the numerical index
  • lookup the word in wordList contained at this index and return it

This pattern of usage would better be served by a Map, where the key would be the input word, possibly corresponding to an entry in stringWordList, and the output another word, from wordList.

A map lookup would be an O(1) operation, as compared to O(N) for the lookups in a list.