0

getTime() method compares Unix times of dates. I don't know how compareTo() method works. Which one is better (faster) and why?

Date date1 = ...
Date date2 = ...

//METHOD 1
if(date1.getTime() == date2.getTime()) {
...
}

//METHOD 2
if(date1.compareTo(date2) == 0) {
...
}
micnyk
  • 726
  • 8
  • 27
  • possible duplicate of http://stackoverflow.com/questions/1551235/java-strings-compareto-vs-equals – Anik Islam Abhi Nov 08 '14 at 10:38
  • 1
    I think in your case it doesn't make any difference. Comparison of two longs is a simple enough operation available in almost all CPUs currently in use on the planet. I would expect that the == variant is slightly faster since compareTo also bothers to compute the kind of (un|)equality (-1,0,1). But remember early optimization is the root of all evil. ;-) – Oncaphillis Nov 08 '14 at 10:57

2 Answers2

2

First method uses one comparison, second method uses on average 3 comparisons(2 from compareTo and 1 from your code)

Lets see sources

public int compareTo(Date date) {
    if (milliseconds < date.milliseconds) {
        return -1;
    }
    if (milliseconds == date.milliseconds) {
        return 0;
    }
    return 1;
}
Dmitry
  • 864
  • 7
  • 15
0

Premise: you wrote that "getTime() method compares Unix times of dates". This is not correct, since that function returns the amount of time as an integer. Hence, you can rely on the first method, that's just a numerical comparison. You won't find nothing faster than this:

if(date1.getTime() == date2.getTime()) {
    ...
}
TheUnexpected
  • 3,077
  • 6
  • 32
  • 62