I recently discovered a hugely inefficient portion of code in my program, and have gone about rewriting it. I am however, not quite sure if the rewritten program actually does exactly what I want, due to its (relative) mathematical complexity. I am especially uncertain about how this new code will handle changes of the day (so 24:00 -> 00:00).
Here are the old and the new piece of code, in said order:
Collections.sort(listEntries, new Comparator<LogEntry>() {
@Override
public int compare(LogEntry lhs, LogEntry rhs) {
Calendar lhsCreatedAt = Calendar.getInstance();
Calendar rhsCreatedAt = Calendar.getInstance();
lhsCreatedAt.setTimeInMillis(lhs.getCreatedAt());
rhsCreatedAt.setTimeInMillis(rhs.getCreatedAt());
if (lhsCreatedAt.get(Calendar.YEAR) != rhsCreatedAt.get(Calendar.YEAR)) {
return rhsCreatedAt.get(Calendar.YEAR) - lhsCreatedAt.get(Calendar.YEAR);
}
if (lhsCreatedAt.get(Calendar.DAY_OF_YEAR) != rhsCreatedAt.get(Calendar.DAY_OF_YEAR)) {
return rhsCreatedAt.get(Calendar.DAY_OF_YEAR) - lhsCreatedAt.get(Calendar.DAY_OF_YEAR);
}
return (int) (lhs.getCreatedAt() - rhs.getCreatedAt());
}
});
versus
Collections.sort(listEntries, new Comparator<LogEntry>() {
@Override
public int compare(LogEntry lhs, LogEntry rhs) {
long lhsCreatedAt = lhs.getCreatedAt();
long rhsCreatedAt = rhs.getCreatedAt();
long millisecondsPerDay = 86400000;
if (Math.floor(lhsCreatedAt/millisecondsPerDay) != Math.floor(rhsCreatedAt/millisecondsPerDay)){
return (int) (rhsCreatedAt - lhsCreatedAt);
}
return (int) (lhsCreatedAt - rhsCreatedAt);
}
});
If there are any flaws in this new code, or any other performance increases to be gained, I would love to know.