This question has long been interested in: is there a difference (in terms of performance) between 2 code fragments?

1st option

XDocument xmlDoc = XDocument.Load("File.xml"); var nodes = xmlDoc.DescendantNodes(); // возвращает IEnumerable<XNode> foreach (XNode node in nodes) { //код } 

2nd option

 XDocument xmlDoc = XDocument.Load("File.xml"); foreach (XNode node in xmlDoc.DescendantNodes()) { //код } 

I can assume that foreach works with an enumerator and there is no difference here, although I may be wrong, so please explain.

And another question: if you declare a variable in a loop, will it be updated with each iteration? For example, a temporary variable needed to store intermediate values.

 for(int i=0;i<N;i++) { int tmp; // для временного хранения в процессе вычислений // некая логика } 

Or do it like this:

 int tmp; // для временного хранения в процессе вычислений for(int i=0;i<N;i++) { // некая логика } 

Explain, please.

2 answers 2

About 1 and 2 options. There will be no difference. Moreover, the compiler most likely will make the first one from the second variant. It is better to write such code as aesthetically beautiful, inside the compiled compiler itself will do everything beautifully. Most likely others will say about these options "premature optimization".

On the second issue. In C #, variables live from the declaration point to the closing brace of the current level. Therefore, in the first variant in each iteration of the cycle there will be its own variable tmp. Outside the loop it will not be available. In the second variant, the variable will be available outside the loop and will be “common” for all its iterations. Usually, in this code example, it is not bad to initialize the tmp variable, for example, zero.

    You are doing irrelevant optimization. The cost of an XDocument.Load is several orders of magnitude greater than the difference between cycles.

    Always run the profiler before optimization, so that it points to those places where a real performance drawdown occurs.

    In your case, the first and second variants of the loop are strictly the same (the optimizer has the right to remove the temporary variable), except that in the first variant, xmlDoc.DescendantNodes() available after the loop. Choose the option that you think is more readable.

    In the same way, nano-optimization like taking out a variable outside the cycle limits will make the optimizer for you, and, believe me, much better than you. Worse, he will notice if the variable values ​​between cycle runs are related, and will cancel the optimization, if needed. Let the car work!