Question

What's the relative efficiency of integer comparison in java?

== >= <= > <

Does it depend on the physical architecture?

Was it helpful?

Solution

Most hardware instruction sets do these comparisons as two instructions a compare followd by a branch depending on the result of the compare. So for most JVMs on most hardware it makes no difference at all whether its <, <=,= >=, > or !=, its the same two instructions with different flags set.

See this question

Of course it entirely depends on the instruction set and how the JVM authors and their C compiler chooses to use it.

OTHER TIPS

I doubt there's a lot of difference. If there is, chances are good that the compiler will transform your expression into the best test. There should be no difference at all if one of the arguments is 0.

If you're doing something where this makes any kind of difference at all, I'd like to know what it is.

Yes, it depends on both your hardware architecture and your JVM: Java runs within a virtual machine which implements the Java Virtual Machine Specification see http://docs.oracle.com/javase/specs/jvms/se7/html/index.html . There are a wide variety of JVMs which all implement java code differently (e.g. those on this list: https://en.wikipedia.org/wiki/List_of_Java_virtual_machines ) Each JVM and processor architecture can implement your code differently, so your exact results will vary according to them.

That said, the other answers are correct that these operators should all be effectively identical in practice with real code. Other operations (such as multiplication, floating point operations and more complex calculation) will have a vastly greater impact on processor time because they are not as simple to carry out.

They are all single opcodes of the form if_acmp<cond>, if_icmp<cond>, if<cond>, etc. in the Java bytecode, and I can't immediately recall any hardware architecture where there were significantly different opcodes either for the various conditions, or different cycle times. In one or two interpreters I have built I saved code space by only implementing <, ==, and >, and doing the others with a following NOT, but that was just for toy languages.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top