简体   繁体   English

JAVA-加速代码

[英]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 . 有一个以上的列表( String ),如_list1_list2_list3

  • I try to find a word ( String ) in these lists. 我尝试在这些列表中找到一个单词( String )。

  • 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 1.用if (i = indexOf(s) >= 0) return i替换if (contains) then indexOf模式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 2.添加查找数据结构(例如Map<String,Integer>并在列表中添加或更改列表时使用它来代替列表或通过更新它来添加列表

Add all your lists ( String ) in a List<String> and iterate on it : List<String>添加所有列表( String )并对其进行迭代:

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. 我以前曾使用过list,现在更改了它。 I use 2D String array. 我使用2D字符串数组。 But code performance was 157% decrease. 但是代码性能却下降了157%。

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. 如果我要查找的代码是“ _list [180] [?]”,则很难找到它。

How can I speed up the my code? 如何加快我的代码?

Thank you. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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