Negating ints in Java

170 views Asked by At

I've seen in a fair amount of Java code something like this:

int blah = ~someFunc() + 1;

instead of

int blah = -1 * someFunc();

is there any real difference in output here? Does javac recognize a difference between these two cases? It seems the compiler should be able to transform these two lines into the same byte code.

Edit: This is not about how bit flips work, it's a question about why an implementer might choose a certain approach to the operation.

Edit2: I did javap -c on a simple test and here's some JVM bytecode:

int one = -1 * someFunc();
0: iconst_m1     
1: invokestatic  #2                  // Method someFunc:()I
4: imul          
5: istore_1      

int two = ~someFunc() + 1;
6: invokestatic  #2                  // Method someFunc:()I
9: iconst_m1     
10: ixor          
11: iconst_1      
12: iadd          
13: istore_2    

So there are 3 more java instructions for the bit flip (which is iconst_m1, ixor) plus one, but how that translates into machine cycles is probably very architecture-specific.

1

There are 1 answers

1
marcelv3612 On

Speaking strictly of the instruction costs, the first approach could indeed be faster (on some processors): For example, visit http://www.agner.org/optimize/instruction_tables.pdf and compare cost of operations:

IMUL r32 = 3 ops
ADD = 1 op
NOT = 1 op

So, you might save one operation. On the other hand, each function call requires you to put vars on register stack and retrieve them from it, which adds additional cost.