javasonarqubesonarqube-scan

Method does not presize the allocation of a collection


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 ?


Solution

  • 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.