gpt4 book ai didi

java - BufferedWriter 性能缓慢

转载 作者:行者123 更新时间:2023-12-02 12:35:50 25 4
gpt4 key购买 nike

我有一种方法可以将 44 MB 的数据从 ResultSet 写入 CSV 文件。然而,完成大约需要 3.5 分钟。对于只有 44 MB 的数据来说,这似乎很慢。任何人都可以看到任何减慢我的代码速度的东西吗?:

public static void convertToCSV(final ResultSet rs) throws SQLException, IOException {
final BufferedWriter fw = new BufferedWriter(new FileWriter(new File("alert.csv")));
while (rs.next()) {
fw.write(rs.getString("FIELD1")+",");
fw.write(rs.getString("FIELD2")+",");
fw.write(rs.getString("FIELD3")+",");
final String clobValue = rs.getString("FIELD4");
if(clobValue==null)
fw.write("null,");
else{
fw.write("\""+clobValue+"\",");
}
final Date date = new Date(rs.getLong("FIELD5"));
final DateFormat format = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
final String dateTime[] = format.format(date).split(" ");
fw.write(dateTime[0]+",");
fw.write(dateTime[1]);

fw.write("\n");
}
fw.close();
}

最佳答案

这样的事情可能会更快

public static void convertToCSV(final ResultSet rs) throws SQLException, IOException {
final BufferedWriter fw = new BufferedWriter(new FileWriter(new File("alert.csv")));
final DateFormat format = new SimpleDateFormat("'yyyyMMdd','HH:mm:ss'");
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));

while (rs.next()) {
StringBuilder sb = new StringBuilder();
sb.append(rs.getString("FIELD1")).append(',')
.append(rs.getString("FIELD2")).append(',')
.append(rs.getString("FIELD3")).append(',');

final String clobValue = rs.getString("FIELD4");
if(clobValue==null)
sb.append("null,");
else{
sb.append('\"').append(clobValue).append('\"').append(',');
}
Date date = new Date(rs.getLong("FIELD5"));
sb.append(format.format(date)).append('\n');
fw.write(sb.toString());
}
fw.close();
}
  1. DateFormat 的创建仅在循环之外完成一次。
  2. 使用StringBuilder
  3. 尽可能避免创建临时对象。

您甚至可以重用StringBuilder,方法是将创建的内容移出循环,并在编写它后执行setLength(0)

关于java - BufferedWriter 性能缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33238704/

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