Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace LINQ_Perf_Test;
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Linq;
- class Program
- {
- static void Main(string[] args)
- {
- // Create a large list of integers
- int size = 5;
- List<int> numbers = Enumerable.Range(1, size).ToList();
- int elementToFind = size; // Element at the end of the list
- Stopwatch stopwatch = new Stopwatch();
- // Wait 2 seconds.
- System.Threading.Thread.Sleep(2000);
- long linqElapsedTicks = LinqTest(numbers, elementToFind, stopwatch);
- stopwatch.Reset();
- long forLoopElapsedTicks = ForLoopTest(numbers, elementToFind, stopwatch);
- // Log results
- Console.WriteLine($"LINQ Any() took {linqElapsedTicks} ticks.");
- Console.WriteLine($"For loop took {forLoopElapsedTicks} ticks.");
- }
- private static long LinqTest(List<int> numbers, int elementToFind, Stopwatch stopwatch)
- {
- stopwatch.Start();
- bool existsWithLinq = numbers.Any(n => n == elementToFind);
- stopwatch.Stop();
- return stopwatch.ElapsedTicks;
- }
- private static long ForLoopTest(List<int> numbers, int elementToFind, Stopwatch stopwatch)
- {
- stopwatch.Start();
- for (int i = 0; i < numbers.Count; i++)
- {
- if (numbers[i] == elementToFind)
- {
- break;
- }
- }
- stopwatch.Stop();
- return stopwatch.ElapsedTicks;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement