Just tried the code below - it looks like method 1 (yours) takes about 320ms on my pc, vs method 2 (mine) 390ms, vs method 3 (Lukas's) 15ms, vs method 4 (MutableDateTime) 310ms... Now the modulo might (?) lead to incorrect results.
public class Test {
private static int NUM_RUN;
public static void main(String[] args) {
Date date = new Date();
List<Runnable> list = new ArrayList<>();
list.add(method3Withs(date));
list.add(method1With(date));
list.add(methodModulo(date));
list.add(methodMutable(date));
NUM_RUN = 100_000;
for (Runnable r : list) {
long start = System.nanoTime();
r.run();
long end = System.nanoTime();
System.out.println((end - start) / 1000000);
}
NUM_RUN = 10_000_000;
for (Runnable r : list) {
long start = System.nanoTime();
r.run();
long end = System.nanoTime();
System.out.println((end - start) / 1000000);
}
}
private static Runnable method3Withs(final Date date) {
return new Runnable() {
@Override
public void run() {
DateTime d2 = null;
for (int i = 0; i < NUM_RUN; i++) {
d2 = new DateTime(date);
d2 = d2.withMinuteOfHour(0);
d2 = d2.withSecondOfMinute(0);
d2 = d2.withMillisOfSecond(0);
}
System.out.println(d2);
}
};
}
private static Runnable method1With(final Date date) {
return new Runnable() {
@Override
public void run() {
DateTime d2 = null;
for (int i = 0; i < NUM_RUN; i++) {
d2 = new DateTime(date);
d2 = d2.withTime(d2.getHourOfDay(), 0, 0, 0);
}
System.out.println(d2);
}
};
}
private static Runnable methodModulo(final Date date) {
return new Runnable() {
@Override
public void run() {
DateTime d2 = null;
for (int i = 0; i < NUM_RUN; i++) {
long truncatedTimestamp = date.getTime() - date.getTime() % 3600000;
d2 = new DateTime(truncatedTimestamp);
}
System.out.println(d2);
}
};
}
private static Runnable methodMutable(final Date date) {
return new Runnable() {
@Override
public void run() {
MutableDateTime m = null;
for (int i = 0; i < NUM_RUN; i++) {
m = new MutableDateTime(date);
m.setMinuteOfHour(0);
m.setSecondOfMinute(0);
m.setMillisOfSecond(0);
}
System.out.println(m);
}
};
}
}
EDIT
I made it 10 million runs after a warm up round of 100,000:
3037
4068
88
2864
The modulo method wins by a large margin, so it seems safe to think it will perform much better in most situations.