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.)

  • `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. – user2864740 Jul 15 '14 at 03:35

3 Answers3

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.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • 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 '14 at 05:50
  • Ah, missed the task reversal. – user2864740 Jul 15 '14 at 08:20
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.

Community
  • 1
  • 1
ForguesR
  • 3,558
  • 1
  • 17
  • 39
0

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

Dwayne Towell
  • 8,154
  • 4
  • 36
  • 49