For (int I = 1, n = tempUser. length; I <n; I ++) and
For (int I = 1,; I <tempUser. length; I ++), is there a big difference in performance? Is it necessary to adopt this method,
Used to for (int I = 1,; I <tempUser. length; I ++), and did not find a big difference in performance between the two,
I tested it immediately and found that the performance was quite different, and even the latter was more efficient.
Although such a result is obtained, it is indeed the opposite to your own mind. Of course, the reply is similar.
Today, I found that a senior blog is responding to this post. He did the test, the content is roughly the same as the problem in the previous post, but he conducted a further test and concluded that in the case of for (int I = 0; I <. b. c. length; I ++), use for (int I = 0, n =. b. c. length; I <n; I ++) is more efficient.
I also did some tests:
Copy codeThe Code is as follows:
Class Program {
Static void Main (string [] args ){
String s;
S = Console. ReadLine ();
While (s! = "0 "){
Person p = new Person (10000000 );
Console. WriteLine ("for (int I = 0; I <lenArray. length; I ++ )");
Console. WriteLine ("Starting ...");
Long l1 = DateTime. Now. Ticks;
For (int I = 0; I <p. Child. Alias. Length; I ++ ){
// Console. Write (lenArray [I]);
}
Long l2 = DateTime. Now. Ticks;
Console. WriteLine ("Ending. \ nTime is:" + (l2-l1). ToString ());
Console. WriteLine ("for (int I = 0, n = lenArray. length; I <n; I ++ )");
Console. WriteLine ("Starting ...");
Long l3 = DateTime. Now. Ticks;
For (int I = 0, n = p. Child. Alias. Length; I <n; I ++ ){
// Console. Write (lenArray [I]);
}
Long l4 = DateTime. Now. Ticks;
Console. WriteLine ("Ending. \ nTime is:" + (l4-l3). ToString ());
S = Console. ReadLine ();
}
Console. Read ();
}
}
The larger the data volume, the larger the class, the more obvious the difference.
Conclusion:The impact should be on the reason why variables need to access the lower-level variables in each loop. If it's just a simple. length may be optimized by the compiler for such loop operations. the length is stored in the memory or a place with more blocks than the memory, and the multi-level is not so lucky.
We all know that for (int I = 0; I <. length; I ++) Statement, I = 0 is run once, And I <. length and I ++ are the tasks of each loop. All operations that require time-consuming access to variables should be placed before the first; number.