我有一个应用程序迭代大量的结果集并从不同的表中查询每一行的附加信息。
大致的结构是这样的:
public void main(String[] args) {
ResultSet result = database.connection.createStatement()
.executeQuery("SELECT * FROM entities");
ArrayList<Entity> entities = new ArrayList<Entity>();
while (result.next() {
Entity entity = EntityFactory.createById(result.getInt("id"));
entities.add(entity);
}
}
// EntityFactory
public static Entity createById(int id) {
StringBuilder sql = new StringBuilder("SELECT * FROM sampling_data WHERE id = ")
.append(id);
ResultSet result = database.connection.createStatement()
.executeQuery(sql.toString());
result.first();
EntityData data = new EntityData(25);
for (int sample = 1; sample <= 25; sample++) {
String sample_R = new StringBuilder("sample_")
.append(sample).append("_R").toString();
String sample_G = new StringBuilder("sample_")
.append(sample).append("_G").toString();
String sample_B = new StringBuilder("sample_")
.append(sample).append("_B").toString();
int r = resultSet.getInt(sample_R);
int g = resultSet.getInt(sample_G);
int b = resultSet.getInt(sample_B);
data.add(r, g, b);
}
return new Entity(data);
}
这会导致 OutOfMemoryException。
如何使循环(或整个方法)的内存效率更高?