Which of the following operations is faster? ( I am looking for a computer-science/theoretical explanation)
boolean value = System.currentTimeMillis() - myTime > TEN_HOURS;
or
boolean value = System.currentTimeMillis() > myTime + TEN_HOURS;
Which of the following operations is faster? ( I am looking for a computer-science/theoretical explanation)
boolean value = System.currentTimeMillis() - myTime > TEN_HOURS;
or
boolean value = System.currentTimeMillis() > myTime + TEN_HOURS;
只是为了好玩,这里有一个你可以自己运行的快速测试:
public class StrangeComparison {
private static final long TEN_HOURS = 1000 * 60 * 60 * 10; // milliseconds -> seconds -> minutes -> hours -> ten
private static final int NUM_COMPARISONS = 10000000;
public static void main(String[] args) {
long myTime = System.currentTimeMillis() - (TEN_HOURS / 2);
long startTime = System.currentTimeMillis();
for (int i = 0; i < NUM_COMPARISONS; i++) {
boolean theValue = System.currentTimeMillis() - myTime > TEN_HOURS;
}
System.out.println("Took " + (System.currentTimeMillis() - startTime) + "ms for Comparison #1");
startTime = System.currentTimeMillis();
for (int i = 0; i < NUM_COMPARISONS; i++) {
boolean theValue = System.currentTimeMillis() > TEN_HOURS + myTime;
}
System.out.println("Took " + (System.currentTimeMillis() - startTime) + "ms for Comparison #2");
}
}
结果输出:
Took 401ms for Comparison #1
Took 400ms for Comparison #2