1

Consider the following 2 (sort of) pseudo code blocks (my question is specific to Java though) -

//BLOCK 1 (using modulo)
for(int i=0,i<N,i++){ //N is in the order of millions
   int temp1 = a%10;
   int temp2 = a/10;
   // more code adding temp1 & temp2, etc.
   }

//BLOCK 2 (using int <-> char conversions)
for(int i=0;i<N;i++) { //N is in the order of millions
    if(a>9){
       String t1 = String.valueOf(a);
       Integer temp1 = Integer.parseInt(t1.CharAt(0));
       Integer temp2 = Integer.parserInt(t2.CharAt(1));
    }
    // more code adding temp1 & temp2, etc.
}

My question is - keeping everything else the same, compare the 2 ways of obtaining temp1 & temp2 in the 2 code blocks above.
Which one is more intensive? I think it should be the modulo but I am not sure. Because string<->int<->char conversions are not CPU intensive I believe. I could be entirely wrong and hence I am posting this question.

(PS. Most of you may have guessed that I am trying to get the 1st and 2nd digits of a 2-digit number and you're correct.)

1
  • Integer.parseInt(char)? I think not; but if you have a single character (e.g. a hex special case) then a lookup or switch is likely faster. Jul 15, 2014 at 3:35

3 Answers 3

1

I think you'll find that converting an integer into a string actually calls the modulo (or division) function quite a bit anyway, so I suspect the string one will be slower. That's on top of the fact that you're doing work with classes rather than primitive types.

But you should measure, not guess! Without measurement, optimisation is a hit-and-miss operation.

Try each of your proposed solutions in a ten-million-iteration loop and time tem. That's a good start.

2
  • 1
    @user2864740, that code you link to is parseInt, turning string into integer. Turning integer into string (the opposite operation) will use modulo (or division), a not inexpensive operation. In OpenJDK, that's done by String.valueOf(int) which calls Integer.toString(int) which calls Integer.getChars() which does use division (and modulo emulated with bit-shifting and subtraction) in a loop.
    – paxdiablo
    Jul 15, 2014 at 5:50
  • Ah, missed the task reversal. Jul 15, 2014 at 8:20
0

The only way to know is test it in your environment.

1
  • 1
    Should be a comment; not enough relevant information provided. Jul 15, 2014 at 3:30
0

Short answer : modulo is clearly faster because you are working with a int.

Long answer : Block 1 uses primitives and block 2 uses classes which adds overhead. It is not very significant for something this simple but it will still requires more cpu cycles. You can have a look at this nice answer about primitives in Java.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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