Performance issues of for each statements in Java 7
Performance of for each statements in Java 7
TodayLeetCodeI made a fully-arranged algorithm question. At that time, I had obtained the correct result in eclipse. However, when I submitted it to Leetcode, I reported"Time Limit Exceeded".
Permutation on Leetcode
I was puzzled at the beginning. I searched for many similar problems in Leetcode, but I did not find the same problems as I encountered. Many of them say that they finally found an error in their own code. As a result, I checked my code issues carefully. Later I found that after removing one of my circular print List codes, I submitted the code again. At that time, I felt very strange, however, if you are not sure about the reason, write it down for now.
Many people said at nightEvernoteVery easy to use. I already gave up Evernote and switchedNoteBut curiosity drove me to try Evernote again, so I went to my Evernote and suddenly saw a previously added blog.Performance Comparison of Three Java list traversal methodsI think of a similar problem today. Then I went to the page and tested it myself. I found that, as the blogger said, the new syntax supported by Java 7 is the most concise code, but the performance is indeed the worst; then think about the problems encountered during the day.
The following code tests the List traversal performance:
package org.phn;import java.util.ArrayList;import java.util.Iterator;import java.util.List;public class TestListPrintTime { public static void main(String[] args) { List
list = new ArrayList
(); long t1, t2; for (int j = 0; j < 10000000; j++) { list.add("aaaaaa" + j); } System.out.println("List first visit method:"); t1 = System.currentTimeMillis(); for (String tmp : list) { // System.out.println(tmp); } t2 = System.currentTimeMillis(); System.out.println("Run Time:" + (t2 - t1) + "(ms)"); System.out.println("List second visit method:"); t1 = System.currentTimeMillis(); for (int i = 0; i < list.size(); i++) { list.get(i); // System.out.println(list.get(i)); } t2 = System.currentTimeMillis(); System.out.println("Run Time:" + (t2 - t1) + "(ms)"); System.out.println("List Third visit method:"); Iterator
iter = list.iterator(); t1 = System.currentTimeMillis(); while (iter.hasNext()) { iter.next(); // System.out.println(iter.next()); } t2 = System.currentTimeMillis(); System.out.println("Run Time:" + (t2 - t1) + "(ms)"); System.out.println("Finished!!!!!!!!"); }}
Result:
It can be seen that the for each statement in Java 7 is very convenient and clear, but the performance is several times worse. You should use it with caution. Leave your mind blank. Some problems may arise in the future.