Incorrect Use of Autoboxing and Unboxing for Performance Critical Operations

Incomplete Base
Structure: Simple
Description

This weakness occurs when a program relies on automatic boxing and unboxing of primitive types within performance-sensitive code sections, causing unnecessary computational overhead and potential resource strain.

Extended Description

Languages like Java and C# provide autoboxing (converting a primitive like `int` to an object like `Integer`) and unboxing (the reverse) to simplify code by handling conversions automatically. While convenient for general use, these operations secretly create new objects and add processing steps that degrade execution speed, especially inside tight loops or high-frequency operations. Using boxed primitives within generic collections or performance-critical areas—such as scientific computing, real-time processing, or low-latency systems—can lead to excessive memory allocation, increased garbage collection, and even resource exhaustion. This practice is best reserved only for bridging the gap between primitive APIs and object-based libraries, not for core computational logic where efficiency is paramount.

Common Consequences 1
Scope: Availability

Impact: DoS: Resource Consumption (CPU)DoS: Resource Consumption (Memory)DoS: Resource Consumption (Other)Reduce Performance

Incorrect autoboxing/unboxing would result in reduced performance, which sometimes can lead to resource consumption issues.

Potential Mitigations 1
Phase: Implementation
Use of boxed primitives should be limited to certain situations such as when calling methods with typed parameters. Examine the use of boxed primitives prior to use. Use SparseArrays or ArrayMap instead of HashMap to avoid performance overhead.
Demonstrative Examples 2
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.

Code Example:

Bad
Java
java
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.
This code uses primitive long which fixes the issue.

Code Example:

Good
Java
java
Applicable Platforms
Languages:
Java : UndeterminedC# : Undetermined
Technologies:
Not Technology-Specific : Undetermined
Modes of Introduction
Implementation
Related Weaknesses
Taxonomy Mapping
  • SEI CERT Oracle Coding Standard for Java
  • ISA/IEC 62443