【问题标题】:How to increase the performance of java code?如何提高java代码的性能?
【发布时间】:2020-04-16 15:04:56
【问题描述】:

我想问如何提高代码性能?我需要获取所有 html 代码并将其保存在 Queue-LinkedList 中。但是在提取过程中,我使用了loop里面的loop O(n^2)。这太慢了。如何改进这段代码?

公共类 ParsingHtml {

private static Queue<Character> queueCharacter = new LinkedList<>();

public static void downloadHtmlCode(String addressUrl) throws IOException {

    InputStream is = null;
    try (BufferedReader bufferedReader =
                 new BufferedReader(new InputStreamReader(is = (new URL(addressUrl)).openStream()))) {
        bufferedReader.lines()
                .filter(str -> !str.isEmpty())
                .forEach(str -> {
                    for (char ch : str.toCharArray())
                        if (ch != ' ') queueCharacter.add(ch);
                });
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    is.close();
   }
}

【问题讨论】:

    标签: java lambda


    【解决方案1】:

    您可以使用flatmap,如下所示,

    bufferedReader.lines()
                .filter(str -> !str.isEmpty())
                .flatMap(str->str.chars().mapToObj(x -> (char) x))
                .filter(ch->ch != ' ')
                .collect(Collectors.toCollection(LinkedList::new));
    

    【讨论】:

      【解决方案2】:

      您的foreach 正在执行映射和收集操作。

      通过map 函数和queue.add 通过collect terminate 函数替换字符串到字符数组的转换。

      -->

      lines().flatmap(String::chars).mapToObj(c -&gt; (char) c).filter(c -&gt; c != ' ').collect(Collections.toCollection(LinkedList::new));

      【讨论】:

      • 抱歉刚刚看到我忘记在空字符串上添加过滤器。但你明白了;-)
      【解决方案3】:

      这里的复杂性不是O(n^2)。在您的代码中,您将每个符号读取两次,而不是 n^2 次。第一次读取是当您读取行时,第二次是当您迭代该行中的符号时。这意味着复杂性是О(n)。您可以在一次阅读中做同样的事情:只需逐个字符地阅读 html 并在阅读时将这些字符放入 Queue 中。

      private static Queue<Character> queueCharacter = new LinkedList<>();
      
      public static void main(String[] args) {
      
          try (InputStream inputStream = new URL(addressUrl).openStream()) {
              BufferedReader buffer = new BufferedReader(new InputStreamReader(inputStream));
              int c = 0;
              while ((c = buffer.read()) != -1) {
                  char character = (char) c;
                  if (character != ' ' && character != '\n') {
                      //filter space and endline symbol
                      queueCharacter.add(character);
                  }
              }
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-20
        • 2016-04-12
        相关资源
        最近更新 更多