Aym*_*ari 1 java sonarqube sonarqube-scan
声纳向我显示了这个错误Performance - Method does not presize the allocation of a collection
方法映射(ResponseEntity)不会预先调整集合的分配
这是代码:
private Set<ResponseDTO> mapping(ResponseEntity<String> responseEntity) {
final Set<ResponseDTO> result = new HashSet<>();
final JSONObject jsonObject = new JSONObject(responseEntity.getBody());
final JSONArray jsonArray = jsonObject.optJSONArray("issues");
for (int i = 0; i < jsonArray.length(); i++) {
final JSONObject innerObject = jsonArray.getJSONObject(i);
final String name = innerObject.optString("key");
result.add(new ResponseDTO().name(name));
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
为什么 Sonar 将此标记为错误以及如何修复它?
好吧,您正在操作一个已知长度的数组并将所有元素添加到该集合中。假设您没有任何重复项,结果集应包含相同数量的元素。
但是,您正在创建一个具有默认初始容量的集合,即new HashSet<>()。这可能会导致需要调整集合的大小,这本身不是问题,但没有必要,因此可能会导致性能下降。
要摆脱这个问题,请new HashSet<>(jsonArray.length())在迭代之前通过创建集合。
| 归档时间: |
|
| 查看次数: |
7881 次 |
| 最近记录: |