首页 > 解决方案 > To use an ArrayList or a LinkedList while looping through a JDBC ResultSet

问题描述

This is a general question as to what kind of list needs to be used to accumulate data while looping through a JDBC ResultSet object.

I work for a project where certain queries return thousands of records. SQL queries are executed using JDBC methods and the resultant values are looped through a ResultSet. The SQL query produces a sorted order.

List<Company> list = new ArrayList<>();
ResultSet rs = statement.execute();
while (rs.next()){ 
 Company company = new Company();
 rs.getString("company_name");
 rs.getInteger("company_id");
 list.add(company);
}

This list is returned to the service layer and data binding is done through JAXB or Jackson ObjectMapper to convert it to an XML format or a JSON object and returned as a part of REST call.

There are ~200 such code snippets where an ArrayList is used to accumulate the resultant data.

Query: Since the list is getting structurally modified with every addition of a new data item, will using a LinkedList instead of ArrayList make any difference? Which one of it can be used to improve the performance?

Note that the list is not manipulated else where in the application. Data is inserted in the data layer and is transformed in the service layer.

标签: javaarraylistcollectionslinked-list

解决方案


ArrayList 可能是此用例的最佳选择。

如果您需要挤压更多性能,您应该使用分析器来确定瓶颈。我敢打赌,增加 fetch 大小将对提高性能产生最大影响。请参阅https://docs.oracle.com/cd/A87860_01/doc/java.817/a83724/resltse5.htm

@tgdavies 关于直接流式传输到 JSON 的评论非常好。避免创建中间数据结构将显着提高性能。缺点是这将是您的应用程序的 API 更改,这可能是一个需要很长时间来协调的官僚程序。

另一种选择是根据返回的平均记录数预先分配 ArrayList,但您绝对应该只在分析器将其识别为问题时才这样做。


推荐阅读