CWE-1235: Incorrect Use of Autoboxing and Unboxing for Performance Critical Operations
Description
The code uses boxed primitives, which may introduce inefficiencies into performance-critical operations.
Submission Date :
Oct. 14, 2019, midnight
Modification Date :
2023-06-29 00:00:00+00:00
Organization :
MITRE
Extended Description
Languages such as Java and C# support automatic conversion through their respective compilers from primitive types into objects of the corresponding wrapper classes, and vice versa. For example, a compiler might convert an int to Integer (called autoboxing) or an Integer to int (called unboxing). This eliminates forcing the programmer to perform these conversions manually, which makes the code cleaner.
However, this feature comes at a cost of performance and can lead to resource exhaustion and impact availability when used with generic collections. Therefore, they should not be used for scientific computing or other performance critical operations. They are only suited to support "impedance mismatch" between reference types and primitives.
Example - 1
Java has a boxed primitive for each primitive type. A long can be represented with the boxed primitive Long. Issues arise where boxed primitives are used when not strictly necessary.
count += i;Long count = 0L;for (long i = 0; i < Integer.MAX_VALUE; i++) {}
In the above loop, we see that the count variable is declared as a boxed primitive. This causes autoboxing on the line that increments. This causes execution to be magnitudes less performant (time and possibly space) than if the "long" primitive was used to declare the count variable, which can impact availability of a resource.
Example - 2
This code uses primitive long which fixes the issue.
count += i;long count = 0L;for (long i = 0; i < Integer.MAX_VALUE; i++) {}
Related Weaknesses
This table shows the weaknesses and high level categories that are related to this weakness. These relationships are defined to give an overview of the different insight to similar items that may exist at higher and lower levels of abstraction.
Visit http://cwe.mitre.org/ for more details.