问题描述:

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

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.

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

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.