Lou pig has the habit of reading other people's code when he is free. He has learned a lot of simple and efficient writing methods and the essence of thinking from many excellent and standardized codes. However, sometimes you may feel that some of the writing methods are quite interesting. For example, if you see a piece of code, you can add a method to the foreach condition judgment. Lou pig initially thought that the method would be executed several times in a loop, which would certainly be efficient. But it seems that I still don't know why the code writer was writing this way. Didn't he accidentally notice this problem, or he was at a low point in rp, or is it because he is not responsible for anything for no reason ?!
Chairman Mao taught us that "there is no right to speak without investigation". I D stressed that the whole society should establish a scientific development concept. Recognizing the seriousness of the problem, Lou pig tested it locally:
Code Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Namespace CSStudy
{
Class Program
{
Private static int executeTimes = 0;
Static void Main (string [] args)
{
Foreach (string item in CreateStrArr () // call the CreateStrArr method here. Will CreateStrArr be executed multiple times?
{
Console. WriteLine (item );
}
Console. WriteLine ("As you see, method CreateStrArr execute times: {0}", executeTimes );
Console. ReadKey ();
}
Static List <string> CreateStrArr ()
{
ExecuteTimes ++; // record how many times the CreateStrArr method has been run
List <string> listResults = new List <string> ();
For (int I = 0; I <5; I ++)
{
ListResults. Add (I + 1). ToString ());
}
Return listResults;
}
}
}
The test results prove that there will be no such thing as hate for no reason or love for no reason in this world ". As shown in the test results, the CreateStrArr method only runs once, and the static CreateStrArr method is changed to the instance method. The effect is the same (forgive me for being in the dark, it was a joke ...), it should not be efficient. The code writer can laugh.
The lost Lou pig checked msdn again. "The foreach statement repeats an embedded statement group for each element in an array or object set. The foreach statement is used to cyclically access the set to obtain the required information, but should not be used to change the set content to avoid unpredictable side effects. obviously, it does not tell us why the method in foreach In the example is only executed once. After logging on to google, I finally found that the compiler optimized the foreach during compilation. Nnd, I thought there was a problem with rp. It turned out to be the magic of the compiler.
Appendix:Find the duplicate value of a field in the table
In the previous iBATIS.net article, we mentioned a person table: