Last active
December 25, 2015 03:49
-
-
Save hazzik/6912865 to your computer and use it in GitHub Desktop.
SelectMany performance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Compiling the source code.... | |
$mcs main.cs -out:demo.exe 2>&1 | |
main.cs(37,13): warning CS0219: The variable `ids1' is assigned but its value is never used | |
main.cs(40,13): warning CS0219: The variable `ids1' is assigned but its value is never used | |
Compilation succeeded - 2 warning(s) | |
Executing the program.... | |
$mono demo.exe | |
SelectMany method chain : 00:00:00.7027228 | |
SelectMany linq : 00:00:00.6438793 | |
Nested foreach : 00:00:00.3397560 | |
AddRange : 00:00:00.0498781 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.IO; | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Diagnostics; | |
class Program { | |
public class PaymentItemViewModel { | |
public List<int> Placements { get; set; } | |
public int StandardPayment { get; set; } | |
} | |
static void Main() { | |
var numbers = Enumerable.Range(0, 4000).ToList(); | |
var models = numbers.Select(n => new PaymentItemViewModel() { | |
Placements = numbers, | |
StandardPayment = n | |
}).ToList(); | |
Test("SelectMany method chain", ()=>Test4(models)); | |
Test("SelectMany linq ", ()=>Test1(models)); | |
Test("Nested foreach ", ()=>Test2(models)); | |
Test("AddRange ", ()=>Test3(models)); | |
} | |
static void Test(string name, Action test) | |
{ | |
var stopwatch = new Stopwatch(); | |
stopwatch.Start(); | |
test(); | |
stopwatch.Stop(); | |
Console.WriteLine(name + " : " + stopwatch.Elapsed); | |
} | |
static void Test1(List<PaymentItemViewModel> models) { | |
var ids1 = models.SelectMany(m => m.Placements).ToList(); | |
} | |
static void Test4(List<PaymentItemViewModel> models) { | |
var ids1 = (from model in models | |
from placement in model.Placements | |
select placement).ToList(); | |
} | |
static void Test2(List<PaymentItemViewModel> models) { | |
var ids2 = new List<int>(); | |
foreach(var model in models) { | |
foreach(var placement in model.Placements) { | |
ids2.Add(placement); | |
} | |
} | |
} | |
static void Test3(List<PaymentItemViewModel> models) { | |
var ids3 = new List<int>(); | |
foreach(var model in models) { | |
ids3.AddRange(model.Placements); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment