c does not need to be boxed here
34 char c = s.charAt(i);
35 if (!(c < 256 && (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= 128 && c <= 237))) {
36 write.append("\\x");
37 write.append(Integer.toHexString((int) c));38 } else {
39 write.append(c);
40 }
Description
A primitive is boxed, and then immediately unboxed. This probably is due to a manual boxing in a place where an unboxed value is required, thus forcing the compiler to immediately undo the work of the boxing.
Needless boxing and unboxing increases the number of dead objects that need to be garbage collected, and should be avoided.
Boxing can occur in the following cases:
- Casting a primitive to a boxed type
- Calling a boxed type's constructor with a primitive value (this is deprecated)
- Calling a boxed type's
valueOf
method with a primitive value
Bad Practice
void checkValue(Integer value) {
if (value > 4) {
// ...
}
}
// ...
int a = 3;
// a is boxed, but is immediately unboxed.
checkValue((Integer)a);
The generated bytecode for such a call looks like this:
iload_1 // load `a` into the stack.
invokestatic #7 // call static method `Integer.valueOf()` with `a`
invokevirtual #13 // call instance method `Integer.intValue()`
invokestatic #17 // call instance method `checkValue()` with `a`
Note that even though the code shows only a cast, javac
outputs two calls, one to Integer.valueOf()
to convert a
into an Integer
, then Integer.intValue()
to convert it back into a primitive int
.
Recommended
Pass in the right argument type. In this case, we just need to pass a
directly to checkValue.
checkValue(a);