【问题标题】:How to optimize java code - run time如何优化 java 代码 - 运行时
【发布时间】:2015-09-15 22:27:54
【问题描述】:

我有以下代码,这花费了我运行时间。关于如何优化它以使其更好更快的任何建议?

                for (int tIndex = 0; tIndex < numTopics; tIndex++) {
                    double beta0 = sumTopicWordCount[tIndex] + betaSum;
                    int m0 = 0;
                    double expectWT = 1;
                    // getting the number of total words (or word w) in sentence i
                    List<String> sentenceStat = new ArrayList<String>();
                    for(int wIndex=0 ; wIndex<sentence.size() ; wIndex++){
                        sentenceStat.add(id2WordVocabulary.get(document.get(sIndex).get(wIndex)));
                    }
                    Set<String> unique = new HashSet<String>(sentenceStat);
                    for(String key : unique){
                        int cnt = Collections.frequency(sentenceStat, key);
                        double betaw = topicWordCount[tIndex][word2IdVocabulary.get(key)] + beta;
                        for (int m = 0; m < cnt; m++) {
                            expectWT *= (betaw + m) / (beta0 + m0);
                            m0++;
                        }
                    }
                    multiPros[tIndex] = (docTopicCount[sIndex][tIndex] + alpha) * expectWT;
                }

【问题讨论】:

    标签: java arrays performance list hashset


    【解决方案1】:

    问题是您在循环中反复扫描数据:Collections.frequency 一遍又一遍地扫描整个列表。

    您可以一次性数出它们,而不仅仅是列出独特的元素。我假设下面是 Java 5-7;在 Java 8 中它会被缩短并且可能更快。

       Map<String, Integer> unique = new HashMap<String, Integer>();
       for(String s: sentenceStat) {
           Integer cnt = unique.get(s);
           if (cnt == null) {
               unique.put(s, 1);
           } else {
               unique.put(s, cnt + 1);
           }
       }
       for(Map.Entry<String, Integer> key : unique.entrySet()){
           String key = entry.getKey();
           int cnt = entry.getValue();
           double betaw = topicWordCount[tIndex][word2IdVocabulary.get(key)] + beta;
           for (int m = 0; m < cnt; m++) {
               expectWT *= (betaw + m) / (beta0 + m0);
               m0++;
           }
       }
    

    【讨论】:

    • 我收到关于 HashMap 的错误 HashMap 类型的参数数量不正确;它不能用参数 参数化
    • 已修复。请注意,我没有测试过代码,它可能包含拼写错误。
    猜你喜欢
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    • 2016-10-04
    • 2011-02-19
    • 2014-10-05
    • 2017-10-18
    相关资源
    最近更新 更多