Advertisement
Guest User

Untitled

a guest
Aug 13th, 2024
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.54 KB | None | 0 0
  1. namespace LINQ_Perf_Test;
  2.  
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Linq;
  7.  
  8. class Program
  9. {
  10.     static void Main(string[] args)
  11.     {
  12.         // Create a large list of integers
  13.         int size = 5;
  14.         List<int> numbers = Enumerable.Range(1, size).ToList();
  15.         int elementToFind = size; // Element at the end of the list
  16.         Stopwatch stopwatch = new Stopwatch();
  17.        
  18.         // Wait 2 seconds.
  19.         System.Threading.Thread.Sleep(2000);
  20.        
  21.         long linqElapsedTicks = LinqTest(numbers, elementToFind, stopwatch);
  22.        
  23.         stopwatch.Reset();
  24.  
  25.         long forLoopElapsedTicks = ForLoopTest(numbers, elementToFind, stopwatch);
  26.  
  27.         // Log results
  28.         Console.WriteLine($"LINQ Any() took {linqElapsedTicks} ticks.");
  29.         Console.WriteLine($"For loop took {forLoopElapsedTicks} ticks.");
  30.     }
  31.  
  32.     private static long LinqTest(List<int> numbers, int elementToFind, Stopwatch stopwatch)
  33.     {
  34.         stopwatch.Start();
  35.         bool existsWithLinq = numbers.Any(n => n == elementToFind);
  36.         stopwatch.Stop();
  37.         return stopwatch.ElapsedTicks;
  38.     }
  39.    
  40.     private static long ForLoopTest(List<int> numbers, int elementToFind, Stopwatch stopwatch)
  41.     {
  42.         stopwatch.Start();
  43.         for (int i = 0; i < numbers.Count; i++)
  44.         {
  45.             if (numbers[i] == elementToFind)
  46.             {
  47.                 break;
  48.             }
  49.         }
  50.  
  51.         stopwatch.Stop();
  52.         return stopwatch.ElapsedTicks;
  53.     }
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement