java - 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.
解决方案
ArrayList 可能是此用例的最佳选择。
如果您需要挤压更多性能,您应该使用分析器来确定瓶颈。我敢打赌,增加 fetch 大小将对提高性能产生最大影响。请参阅https://docs.oracle.com/cd/A87860_01/doc/java.817/a83724/resltse5.htm
@tgdavies 关于直接流式传输到 JSON 的评论非常好。避免创建中间数据结构将显着提高性能。缺点是这将是您的应用程序的 API 更改,这可能是一个需要很长时间来协调的官僚程序。
另一种选择是根据返回的平均记录数预先分配 ArrayList,但您绝对应该只在分析器将其识别为问题时才这样做。
推荐阅读
- database - Sqlite> 未出现在 Git Bash 终端中
- regex - 无法解析多行正则表达式模式
- javascript - 使用 Socket io 拖放
- java - Java 将通配符转换为模板类型
- mysql - 如何为codeigniter中的同一列创建MULTIPLE LIKE查询?
- reactjs - 使用 RTK 查询 Redux 获取数据
- discord - Discord Bot:使用用户生成的数字作为整数输入
- python - Pyinstaller 只有 .exe,没有别的
- python - Tesseract 输出从非常清晰的图像中更改、添加和删除数字
- r - 将自定义输出层添加到 R 中的内置(功能)keras 模型