What's fast: Query syntax versus loops

The following code presents two approaches that generate pairs of integers whose sum is less than 100, and they are arranged in descending order based on their distance from (0,0).

//approach 1 private static IEnumerable<Tuple<int,int>> ProduceIndices3() { var storage = new List<Tuple<int, int>>(); for (int x = 0; x < 100; x++) { for (int y = 0; y < 100; y++) { if (x + y < 100) storage.Add(Tuple.Create(x, y)); } } storage.Sort((p1,p2) => (p2.Item1 * p2.Item1 + p2.Item2 * p2.Item2).CompareTo( p1.Item1 * p1.Item1 + p1.Item2 * p1.Item2)); return storage; } //approach 2 private static IEnumerable<Tuple<int, int>> QueryIndices3() { return from x in Enumerable.Range(0, 100) from y in Enumerable.Range(0, 100) where x + y < 100 orderby (x * x + y * y) descending select Tuple.Create(x, y); } 

This code is taken from Bill Wagner's Effective C # book, paragraph 8. Throughout the article, the author paid more attention to the syntax, compactness and readability of the code, but paid very little attention to the presentation and hardly discussed it.

So, I basically want to know which approach is faster? And what is usually better at execution (in general): Query syntax or Manual loops?

Please discuss them in detail by providing links, if any. :-)

+4
source share
3 answers

Profiling is true, but my gut feeling would be that the loops are probably faster. The important thing is that 99 times out of 100, the difference in performance is simply not important in the great scheme of things. Use a more readable version, and your future will be grateful to you when you need to support it later.

+9
source

Execution of each function 1000 times:

for cycle: 2623 ms request: 2821 ms

It looks logical, because the second is just syntactic sugar for the first. But I would use the second for its readability.

+4
source

Although this does not give a rigorous answer to your question, I would suggest reducing this logic x + y to iteration, in this way:

 for (int x = 0; x < 100; x++) for (int y = 0; y < 100 - x; y++) storage.Add(Tuple.Create(x, y)); 
+1
source

Source: https://habr.com/ru/post/1336370/


All Articles