测试代码 for (int j = 0; j < 30; j++) { long current = System.currentTimeMillis(); for (long i = 0; i < 1000000000; i++) { getPriority(10); } long first = System.currentTimeMillis(); for (long i = 0; i < 1000000000; i++) { getPriority1(10); } long second = System.currentTimeMillis(); System.out.println("first= " + (first - current) + " second= " + (second - first)); }
原方法 private static int getPriority(int cameraType) { switch (cameraType) { case 4: return CameraType.CAMERA_1.getPriority(); case 5: return CameraType.CAMERA_2.getPriority(); case 6: return CameraType.CAMERA_3.getPriority(); case 7: return CameraType.CAMERA_4.getPriority(); case 8: return CameraType.CAMERA_5.getPriority(); case 9: return CameraType.CAMERA_6.getPriority(); case 10: return CameraType.CAMERA_7.getPriority(); default: return -1; } }
private static int getPriority1(int cameraType) { for (CameraType cameraType1 : CameraType.values()) { if (cameraType1.getCameraType() == cameraType) { return cameraType1.getPriority(); } } return -1; }
所用枚举类型 public enum CameraType { CAMERA_1("相机 1", 4, 0), CAMERA_2("相机 2", 5, 2), CAMERA_3("相机 3", 6, 3), CAMERA_4("相机 4", 7, 4), CAMERA_5("相机 5", 8, 5), CAMERA_6("相机 6", 9, 6), CAMERA_7("相机 7", 10, 1); private final String mCameraName; private final int mCameraType; private final int mPriority;
CameraType(String name, int cameraType, int priority) { mCameraName = name; mCameraType = cameraType; mPriority = priority; }
public String getCameraName() { return mCameraName; }
public int getCameraType() { return mCameraType; }
# for of 1. 循环 Array 会带来检查数组边界的开销,每次访问元素都要 check condition 2. getCameraType 是函数,函数需要跳转过去,再跳转回来 3. 发生了额外的三次内存访问,a) 堆获取枚举静态数组, b) 根据数组下标访问枚举对象引用, c) 根据对象引用访问堆内存地址取属性