今天回想起一道java面試題:java
用最有效率的方法算出2乘8等於幾?面試
答案是2 << 3,使用位運算,至關於乘以了2^3。bash
跟朋友在這個問題上討論起來了,有人說java的編譯器會把/2,/4,/8這種涉及2的冪的運算,優化爲位運算。在網上查詢發現沒有多少相關文章,抱着探究精神,決定手動測試一番。測試
public class Main {
public static void main(String[] args) {
Main.testDivision();
Main.testShift();
}
/** * 除法測試 */
private static void testDivision() {
long startTime = System.nanoTime();
int tem = Integer.MAX_VALUE;
for (int i = 0; i <1000000000 ; i++) {
tem = tem / 2;
}
long endTime = System.nanoTime();
System.out.println(String.format("Division operations consumed time: %f s", (endTime - startTime) / 1000000000.0));
}
/** * 位運算測試 */
private static void testShift() {
long startTime = System.nanoTime();
int tem = Integer.MAX_VALUE;
for (int i = 0; i <1000000000 ; i++) {
tem = tem >> 1;
}
long endTime = System.nanoTime();
System.out.println(String.format("Shift operations consumed time: %f s", (endTime - startTime) / 1000000000.0));
}
}
複製代碼
總共測試了3次:優化
// 第一次
Division operations consumed time: 1.023045 s
Shift operations consumed time: 0.264115 s
// 第二次
Division operations consumed time: 1.000502 s
Shift operations consumed time: 0.251574 s
// 第三次
Division operations consumed time: 1.056946 s
Shift operations consumed time: 0.262253 s
複製代碼
根據耗時,得出結論:java編譯器沒有把/2優化爲位運算。spa
java中取模/取餘操做符是%,一般取模運算也叫取餘運算,他們都遵循除法法則,返回結果都是左操做數除以右操做數的餘數。code
public class Main {
public static void main(String[] args) {
Main.testModulo();
Main.testShift();
}
/** * 取模測試 */
private static void testModulo() {
long startTime = System.nanoTime();
int tem = Integer.MAX_VALUE;
for (int i = 0; i <1000000000 ; i++) {
tem = tem % 2;
}
long endTime = System.nanoTime();
System.out.println(String.format("Modulo operations consumed time: %f s", (endTime - startTime) / 1000000000.0));
}
/** * 位運算測試 */
private static void testShift() {
long startTime = System.nanoTime();
int tem = Integer.MAX_VALUE;
for (int i = 0; i <1000000000 ; i++) {
tem = tem & 1;
}
long endTime = System.nanoTime();
System.out.println(String.format("Shift operations consumed time: %f s", (endTime - startTime) / 1000000000.0));
}
}
複製代碼
總共測試了3次:orm
// 第一次
Modulo operations consumed time: 0.813894 s
Shift operations consumed time: 0.003005 s
// 第二次
Modulo operations consumed time: 0.808596 s
Shift operations consumed time: 0.002247 s
// 第三次
Modulo operations consumed time: 0.825826 s
Shift operations consumed time: 0.003162 s
複製代碼
根據耗時,得出結論:java編譯器沒有把對2的取模/取餘操做優化爲位運算。編譯器
感謝閱讀,若是本文陳述的內容存在問題,歡迎和我交流!-- JellyfishMIX@qq.comstring