【发布时间】:2015-10-20 13:57:03
【问题描述】:
我有一个方法可以将 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();
}
【问题讨论】:
-
增加获取 ResultSet 的 Statement 的获取大小可能在一定程度上有所帮助 - 默认情况下,它会返回数据库以每 10 行获取更多数据。权衡是,如果增加 fetch 大小,也会增加内存占用。
-
真的很慢吗,涉及到很多 JDBC 代码,你正在做很多 String concats 生成很多需要 gc'd 的字符串。尽管日期格式不是线程安全的,但我只会在此方法中构造一次并重用。并且可能使用
StringBuilder创建一个字符串并一次性写入。 -
不写数据的情况下,你测过时间,把SimpleDateFormat移出循环吗?
-
您还可以测量写入虚拟数据所需的时间,而无需从数据库中获取数据。
标签: java file csv io bufferedwriter