方法不会预先确定集合的分配大小

问题描述 投票:0回答:1

声纳向我显示此错误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;
}

Sonar为什么将其标记为错误,我该如何解决?

java sonarqube sonarqube-scan
1个回答
2
投票

嗯,您正在对已知长度的数组进行操作,并将所有元素添加到集合中。假设您没有任何重复项,则结果集应包含相同数量的元素。

但是,您正在创建具有默认初始容量(即new HashSet<>())的集合。这可能会导致需要调整集合的大小,这本身不是问题,但不必要,因此could会导致性能下降。

要消除这一点,请在迭代之前立即通过new HashSet<>(jsonArray.length())创建集合。

© www.soinside.com 2019 - 2024. All rights reserved.