1

Consider the following (imaginary) code extract:

class X {
   private static String IS_PAYLOAD_REQUIRED = "4001";
   [....] 
   checkPayloadRequired(String input) {
     if (input.startsWith(IS_PAYLOAD_REQUIRED)) {
       settings.enable(Integer.valueOf(IS_PAYLOAD_REQUIRED).intValue());
     }
   }
 }

IS_PAYLOAD_REQUIRED is required both as a String and an int. The code above delares a String constant and converts to int at runtime when necessary. This conversion is cheap but unnecessary.

Is it worth trying to avoid the conversion? I can think of the following two ways of doing it. Appreciate any comments on usefulness of either.

1: Declare Two variables

private static String IS_PAYLOAD_REQUIRED = "4001";
private static String IS_PAYLOAD_REQUIRED_INT = Integer.valueOf(IS_PAYLOAD_REQUIRED).intValue();

Now use one of the two constants.

2: Create a StringAndInt class private static StringAnInt IS_PAYLOAD_REQUIRED = new StringAnInt(4001);

Use IS_PAYLOAD_REQUIRED.intValue() or IS_PAYLOAD_REQUIRED.stringValue(). I am not showing the implementation of the class here because it is trivial.

The second is obviously safer but I am wondering if it is an overkill.

  • 2
    One advantage of making the constant an int and converting to String before comparing is that no one will try to get clever and change it to "4001A". (Which in your example, would generate no exceptions.) Also, it may be that the compiler is smart enough to only do that conversion once. – Steven Burnap Mar 9 '15 at 20:31
3

Is it worth trying to avoid the conversion?

It depends. This is one of those cases where the "first, measure" sort of advice comes into play. If your profiler says it's an issue, then yes. If not, then I would say no - it's readable enough with the conversion.

The second is obviously safer but I am wondering if it is an overkill.

Yes. If you're using constants, rather than passing around something that regularly needs converted between the two values (and CPU needs optimized more than space), then having two constants is fine. It's readable, it's unlikely to get out of sync, and it's very likely to address performance problems.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.