问题
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