CWE-1235: Incorrect Use of Autoboxing and Unboxing for Performance Critical Operations

Export to Word

Description

The code uses boxed primitives, which may introduce inefficiencies into performance-critical operations.

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.


ThreatScore

Threat Mapped score: 1.9

Industry: Finiancial

Threat priority: P3 - Important (Medium)


Observed Examples (CVEs)

Related Attack Patterns (CAPEC)

N/A


Attack TTPs

N/A

Modes of Introduction

Phase Note
Implementation The programmer may use boxed primitives when not strictly necessary.

Common Consequences

Potential Mitigations

Applicable Platforms


Demonstrative Examples

Intro: 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.

Body: 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.

Long count = 0L; for (long i = 0; i < Integer.MAX_VALUE; i++) { count += i; }

Intro: This code uses primitive long which fixes the issue.

long count = 0L; for (long i = 0; i < Integer.MAX_VALUE; i++) { count += i; }

Notes

← Back to CWE list