Skip to content

Instantly share code, notes, and snippets.

@pictos
Created April 19, 2020 00:00
Show Gist options
  • Save pictos/4ee972b09c37bfcde8b11c76c2ddd80a to your computer and use it in GitHub Desktop.
Save pictos/4ee972b09c37bfcde8b11c76c2ddd80a to your computer and use it in GitHub Desktop.
using BenchmarkDotNet.Attributes;
using Microsoft.Diagnostics.Tracing.Parsers.Clr;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BenchmarkDotNet.Samples.Forms
{
[MemoryDiagnoser]
public class PerfTest
{
public List<int> numbers = new List<int>(10) { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
public Func<int, bool> func = x => x % 2 == 0;
[Benchmark]
public void LinqWhere()
{
numbers.Where(func);
}
[Benchmark]
public void ForEachWhere()
{
numbers.Where(func);
}
[Benchmark]
public void WhileWhere()
{
numbers.Where(func);
}
}
public static class Other
{
public static IEnumerable<T> ForEachWhere<T>(this IEnumerable<T> collection, Func<T, bool> func)
{
foreach (var item in collection)
{
if (func(item))
yield return item;
}
}
public static IEnumerable<T> WhileWhere<T>(this IEnumerable<T> collection, Func<T, bool> func)
{
var enumerator = ((IEnumerable)collection).GetEnumerator();
while (enumerator.MoveNext())
{
var current = (T)enumerator.Current;
if (func(current))
yield return current;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment