| found through the Code test, the performance of try catch in a loop is higher than that in a loop, while I always thought that try catch outside the loop is better than that in a loop. In addition, JDK tests of different versions show that JDK 7 is better than JDK 6, but if try catch is not used, JDK 6 performs a little better than JDK 7. We hope to discuss this with you. The following is my test code. JDK 1.6.0 _ 34 x64 and JDK 1.7.0 _ 09 x64 are used respectively, the server mode is enabled during the test. Run the following commands: JAVA-server-CP .; com. test. main test environment: OS: win7 flagship x64 CPU: 2.0 GB (i7 second generation) memory: 20G (1600 ddr3) |
|
Public static void main (string [] ARGs) {main ins = new main (); int size = 10000000; ins. method1 (size); ins. method2 (size); ins. method3 (size);} public void Method1 (INT size) {long start = system. currenttimemillis (); arraylist <string> Al = new arraylist <string> (); string STR = NULL; try {for (INT I = 0; I <size; I ++) {STR = "str" + I; Al. add (STR) ;}} catch (exception e) {} system. out. println ("Method1 Total:" + (system. currenttimemillis ()-Start);} public void method2 (INT size) {long start = system. currenttimemillis (); arraylist <string> Al = new arraylist <string> (); string STR = NULL; For (INT I = 0; I <size; I ++) {try {STR = "str" + I; Al. add (STR);} catch (exception e) {}} system. out. println ("method2 Total:" + (system. currenttimemillis ()-Start);} public void method3 (INT size) {long start = system. currenttimemillis (); arraylist <string> Al = new arraylist <string> (); string STR = NULL; For (INT I = 0; I <size; I ++) {STR = "str" + I; Al. add (STR);} system. out. println ("method3 Total:" + (system. currenttimemillis ()-Start ));}
Test results:
JDK 7:
Method1 Total: 9846 [placed outside the loop]
Method2 Total: 1266 [placed in a loop]
Method3 Total: 1523 [do not use try catch]
JDK 6:
Method1 Total: 3457 [placed outside the loop]
Method2 Total: 3280 [placed in a loop]
Method3 Total: 1323 [do not use try catch] I personally think it is determined by the business to put it out.