简体   繁体   中英

What is more efficient “||” or a loop?

Let just say you have to edit a series of words from an arraylist("cat", "dog", "catdog", "mandog")

Now you can either put it into a for loop like so

 for(int i=0; i<arraylist.size(); i++){
    if(arraylist.get(i).matches("cat") || arraylist.get(i).matches("dog") etc.. etc..
      {
        //do something
      }
   }

Or you can put the words(cat, dog, catdog and mandog) into a string array/arraylist and compare them using that.

Which one is more efficient?

Taking into consideration that the list of words could be pretty big.

Thanks for the help.

Neither, performance difference will be negligible, both of them are linear in time in the size of the keywords list.

Considering the list of words could become pretty big, you should use a Set . A HashSet can perform a contains check in constant time, making it very suitable for this purpose. So:

Set<String> keywords = new HashSet<>();

keywords.add("cat");
keywords.add("dog");
// ...

for (String element: arraylist) {
    if (keywords.contains(element)) {
        // Do something
    }
}

Note that using matches as you do is actually the same as using equals , so we can simply test for equality.

I think the appropriate way (although alot more work) is to test all the options. Use a profiler to see how much time it takes your code to perform the lookups and then go with the process that yields the best results.

Without using a profiler, it is very hard to determine improvements in performance.

Since you are using a matches() method in your code I assume you need to do a match against a regex. If that is the case you could go for a nested for-loop.

String[] patterns = {"cat", "dog"};
for(String item : arraylist){
    for(String pattern : patterns){
        if(item.matches(pattern)){
            //do something
        }
    }
}

If you just want to check whether the string is present in the list you could go with Stefano Sanfilippo approach.

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