gpt4 book ai didi

java - 优化输入流读取速度更快/提高串联速度

转载 作者:行者123 更新时间:2023-12-01 13:15:13 25 4
gpt4 key购买 nike

目前我正在读取 100,0000+/- 行输入(例如: http://pastebin.com/zhuHLcvA ),其以单个“;”结尾。

使用此代码在我的电脑上读取需要 20 秒以上(这太长了):

public static String readFromStandardIO() {

String returnValue = "";

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
String userInput;
// System.out.println("Enter polynomials:\n");
while (true) {
userInput = reader.readLine();
// System.out.println(userInput);
returnValue = returnValue.concat(userInput);
if (userInput.equals(";")) {
break;
}
}

} catch (Exception e) {

}

return returnValue;

}

使用计时方法我得到奇怪的结果:

long start = System.nanoTime();
pol = readFromStandardIO();
long elaspedTime = System.nanoTime() - start;
System.out.println("reading stream took: " + elaspedTime);

它输出:

reading stream took: 1914854722

行连接似乎减慢了一切:

returnValue = returnValue.concat(userInput)

没有它,一切都是瞬时的。

如何提高串联速度?

最佳答案

public static String readFromStandardIO() {
StringBuilder returnValue = new StringBuilder(9999999);
try {
BufferedReader reader = new BufferedReader(System.in);
String userInput;
while ((userInput = reader.readLine()) != null) {
returnValue.append(userInput);
}
reader.close();
} catch (Exception e) {

}
return returnValue.toString();
}

或者这个更快(如果你的jdk支持*.nio):

public static String readFromStandardNIO() {
java.nio.ByteBuffer buffer = java.nio.ByteBuffer.allocate(20480000);
try {
ReadableByteChannel channel = Channels.newChannel(System.in);
channel.read(buffer);
channel.close();
} catch (Exception e) {

}
return new String(buffer.array());
}

关于java - 优化输入流读取速度更快/提高串联速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22524780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com