Method does not presize the allocation of a collection

泪湿孤枕 提交于 2020-07-03 05:06:49

问题


Sonar shows that me this bug Performance - Method does not presize the allocation of a collection

Method mapping(ResponseEntity) does not presize the allocation of a collection

Here is the code:

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;
}

Why does Sonar flag this as an error and how can I fix it ?


回答1:


Well, you're operating on an array of known length and add all elements to the set. Assuming you don't have any duplicates the resulting set should contain the same number of elements.

However, you're creating a set with a default initial capacity, i.e. new HashSet<>(). That might cause the need for the set to be resized which isn't a problem in itself but would be unnecessary and thus could cause some performance hit.

To get rid of that, create the set via new HashSet<>(jsonArray.length()) right before iterating.



来源:https://stackoverflow.com/questions/59580208/method-does-not-presize-the-allocation-of-a-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!