我需要解析一个来自先前查询的巨大ResultSet,我想出了一些东西,但它太慢了。ResultSet解析器太慢
public LinkedList<CountryFirstData> sortCountryFirst() throws SQLException {
long parsingStart = System.nanoTime();
LinkedList<CountryFirstData> list = new LinkedList<CountryFirstData>();
String serie;
String unit;
String country;
BigDecimal value;
int year;
int index;
while (rs.next()) {
serie = rs.getString(1); // rs is the previously built resultSet
unit = rs.getString(2);
country = rs.getString(3);
value = rs.getBigDecimal(4);
year = rs.getInt(5);
if ((index = list.indexOf(new CountryFirstData(country, serie, unit))) != -1) {
list.get(index).getDuo().add(new YearValueDuo(year, value));
}
else {
CountryFirstData data = new CountryFirstData(country, serie, unit);
data.getDuo().add(new YearValueDuo(year, value));
list.add(data);
}
}
long parsingEnd = System.nanoTime();
Collections.sort(list);
long sortEnd = System.nanoTime();
System.out.println("Parsing Time = " + ((parsingEnd - parsingStart)/1000000000)); // gives 112s
System.out.println("Sorting Time = " + ((sortEnd - parsingEnd)/1000000000)); // gives 0s
return list;
}
我会尽量解释一下代码:
ResultSet中列包含5个不同的值。第一个要考虑的三人组成为country
,serie
和unit
。当我第一次得到这样一个三人组(else
案例)时,我需要创建一个新的CountryFirstData
,并将resultSet行中的剩余年份/值添加到创建的对象中的YearValueDuo
列表字段。
当三人country
,serie
和unit
在list
(if
情况下)已经存在,我需要找回它,两人年/值添加到其YearValueDuo
名单。
所以,基本上,resultSet rs是4000行,整个解析(排除排序)需要2分钟。我觉得这只有4k线太多了。排序仍然很快(不到一秒)。
我选择LinkedList
代替CountryFirstData
而不是ArrayList
,因为后来我按顺序在文件中写入了整个列表(这非常快)。
你们可以建议我一些改进吗?
你为每一行执行''list.indexOf(new CountryFirstData(country,serie,unit))''''。根据“CountryFirstData.equals”的复杂程度,当“list”有3999个条目时,这可能需要很长时间。尝试测量每个行的“indexOf”方法的时间。 – f1sh
@ f1sh Will do,ty。我还没有找到更好的方法来测试列表中是否存在指定的'CountryFirstData'。 – Fitz
比较(在列表中)一个对象实例,添加另一个对象似乎很难看。 –