0

I was wondering how big is speed difference in object vs. primitive comparison. Imagine this piece of code from linked list implementation, which method is "better" to use?

int size = 0;
Node head;

boolean isEmpty1() {
   return head == null;
}

boolean isEmpty2() {
   return size == 0;
}
LukeM
  • 13
  • 1
  • 3
    Use the one you want. It won't make any difference. – JB Nizet May 26 '17 at 07:31
  • It's more efficient to use primitives: https://stackoverflow.com/a/5199425/2115684 - You can check this yourself in a unit test. For your example however, because of the simple `==` check rather than a `.equals()`, it shouldn't be much different. – Jonathan Sterling May 26 '17 at 07:32
  • @JonathanSterling this is not quite the same as the given problem. Look at [Stephen C's answer](https://stackoverflow.com/a/44196063/4216641) for some details. – Turing85 May 26 '17 at 07:33
  • @JonathanSterling this is a totally unrelated issue. OP compares object references here. – Henry May 26 '17 at 07:33
  • @JonathanSterling - That is comparing `int == int` versus `Integer == int`. The second case has the overhead of unboxing. – Stephen C May 26 '17 at 07:34
  • I edited my comment within seconds, but still got caught out :-p. In general terms, it's better to use primitives where possible. However, in this example, it doesn't really matter. – Jonathan Sterling May 26 '17 at 07:34
  • Again ... the "use primitives" advice applies *only* to boxed versus unboxed types. For other cases, you need to analyse the specifics. – Stephen C May 26 '17 at 07:38

1 Answers1

3

Comparison of int values and comparison of reference values using == should take the same time on a modern 32bit or 64bit machine.


I should also point out that premature micro-optimization is typically a bad idea. Unless you are an extraordinary programmer, your intuition on what is faster and what needs to be optimized will be less than perfect. The chances are that if you optimize based on your intuition (or our intuition!) you will waste a lot of time with little measurable benefit.

Graham
  • 7,431
  • 18
  • 59
  • 84
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216