I tried doing the same thing using Linq and non-Linq methods and found out that Linq is significantly slower (~3000x).
Why is that?
Linq way:
for (int i = 0; i < totalElements; i += stepSize)
{
var currentBlock = testList
.Skip(i)
.Take(stepSize);
result.Add(currentBlock.Sum());
}
result.ToList();
Non-Linq way:
for (int i = 0; i < totalElements; i += stepSize)
{
var currentBlock = testList.GetRange(i, stepSize);
result2.Add(currentBlock.Sum());
}
result2.ToList();
Results:
Method: Linq, Time taken: 26667 ms, Elements: 1000000, Step Size: 100
Method: GetRange, Time taken: 9 ms, Elements: 1000000, Step Size: 100
Full source code as requested:
static void Main(string[] args)
{
var totalElements = 1000000;
var testList = new List<int>(totalElements);
var rand = new Random();
// Initialize the list to random integers between 1 and 1000
for (int i = 0; i < totalElements; i++)
{
testList.Add(rand.Next(1, 1000));
}
var result = new List<int>();
var stepSize = 100;
var stp = new Stopwatch();
stp.Start();
for (int i = 0; i < totalElements; i += stepSize)
{
var currentBlock = testList
.Skip(i)
.Take(stepSize);
result.Add(currentBlock.Sum());
}
result.ToList();
stp.Stop();
Console.WriteLine($"Method: Linq, Time taken: {stp.ElapsedMilliseconds} ms, Elements: {totalElements}, Step Size: {stepSize}");
stp.Reset();
var result2 = new List<int>();
stp.Start();
for (int i = 0; i < totalElements; i += stepSize)
{
var currentBlock = testList.GetRange(i, stepSize);
result2.Add(currentBlock.Sum());
}
result2.ToList();
stp.Stop();
Console.WriteLine($"Method: GetRange, Time taken: {stp.ElapsedMilliseconds} ms, Elements: {totalElements}, Step Size: {stepSize}");
}