[pre]public class A {public static final String S_CONSTANT_ABC = \"ABC\";public boolean methodA(String sParam1){if(A.S_CONSTANT_ABC.equalsIgnoreCase(sParam1)){return true;}return false;}}[/pre]
[pre]public class BadCode { public static void calculationWithPrint(){ double someValue = 0D;for (int i = 0; i < 10000; i++) { System.out.println(someValue = someValue + i); }public static void calculationWithOutPrint() { double someValue = 0D;for (int i = 0; i < 10000; i++){ someValue = someValue + i; } } public static void main(String [] n){ BadCode.calculationWithPrint(); BadCode.calculationWithOutPrint(); }[/pre]
在下面的表格中,你能够看到calculationWithOutPrint()方法的运行花了0.001204秒。相比较而言,运行calculationWithPrint()方法花了令人惊讶的10.52秒。
(如果你不知道怎么得到一个像这样的表格,请参阅我的文章“Java Profiling with WSAD” Java Profiling with WSAD)
避免这样一个CPU浪费的最好方法是引入一个包装器方法,就象下面这样
[pre]public class BadCode {public static final int DEBUG_MODE = 1;public static final int PRODUCTION_MODE = 2;public static void calculationWithPrint(int logMode){double someValue = 0D;for (int i = 0; i < 10000; i++) {someValue = someValue + i;myPrintMethod(logMode, someValue);}}public static void myPrintMethod(int logMode, double value) {if (logMode > BadCode.DEBUG_MODE) { return; }System.out.println(value);}public static void main(String [] n) {BadCode.calculationWithPrint(BadCode.PRODUCTION_MODE);}}[/pre]