Iterating a huge list better alternative approach

3286 views java

I have a text input where users enter a search word, I split this search word into a String Array of words, search the list items' name & description using these search words. Here is my code but it's running really slow on my devices. (I double checked that the slowness is from the for each loop not the RecyclerView). Can any one suggest my a good example of a better/faster alternative ?

ArrayList<CustomItem> original_list = getListFromDatabase();
    ArrayList<CustomItem> filtered_list = new ArrayList<>();

    String input_word = search_word.trim().toLowerCase(); // search_word is assigned by an input field
    String[] parts = input_word.split(" ");

    if (original_list != null) {
        for (CustomItem item : original_list) {
            int number = 0;
            for (String part : parts) {

                if (item.getName().toLowerCase().contains(part) || item.getDescription().toLowerCase().contains(part)) {
            if (number == parts.length) filtered.add(item);

    // lastly I assign my filtered list to a RecyclerView

    if (adapter != null);

answered question

The slowness comes from toLowerCase() of item.getName().toLowerCase() and item.getDescription().toLowerCase(). For each iteration, it needs to generate a new String in memory with lower case. Think of some ways to avoid that. One way is to keep a lower case list instead.

1 Answer


There are a few simple things, such as: you are calling toLowerCase() repeatedly for each item. You should do that once before that inner loop!

But beyond that, there isn't much left but (potential) usage of multiple threads, to process multiple parts of your data in parallel. But that won't help on small devices with slow CPUs.

Beyond that, other solutions would require to step back: sometimes you have to design your complete data model to support your most performance critical use cases. If the above computations happen very often, it might be useful to store lower cased strings already, to avoid the overhead of doing that later on.

posted this

Have an answer?


Please login first before posting an answer.