[英]How to increase the performance of java code?
我想問如何提高代碼性能? 我需要獲取所有 html 代碼並將其保存在 Queue-LinkedList 中。 但是在提取過程中,我使用了loop里面的loop O(n^2)。 這太慢了。 如何改進此代碼?
公共 class 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();
}
}
您的foreach
正在執行 map 並收集操作。
通過map
function 和queue.add
by collect terminate function 替換字符串到字符數組的轉換。
-->
lines().flatmap(String::chars).mapToObj(c -> (char) c).filter(c -> c.= ' ').collect(Collections:toCollection(LinkedList:;new));
您可以使用如下flatmap
,
bufferedReader.lines()
.filter(str -> !str.isEmpty())
.flatMap(str->str.chars().mapToObj(x -> (char) x))
.filter(ch->ch != ' ')
.collect(Collectors.toCollection(LinkedList::new));
這里的復雜性不是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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.