Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System.ComponentModel;
using System.Linq;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Attributes.Exporters;
using BenchmarkDotNet.Running;
[MemoryDiagnoser]
[MarkdownExporter]
public class PropertyChangedArgBenchmarks
{
private NormalClass[] normal;
private CachedClass[] cached;
[Setup]
public void SetupData()
{
normal = Enumerable.Range(0, ModelCount).Select(i => new NormalClass()).ToArray();
foreach (var item in normal)
item.PropertyChanged += EmptyHandler;
cached = Enumerable.Range(0, ModelCount).Select(i => new CachedClass()).ToArray();
foreach (var item in cached)
item.PropertyChanged += EmptyHandler;
}
[Params(10, 100, 1000)]
public int ModelCount { get; set; }
[Params(10, 100, 1000, 5000)]
public int ChangeCount { get; set; }
[Benchmark]
public void Normal()
{
for (int i = 0; i < ChangeCount; i++)
for (int j = 0; j < ModelCount; j++)
normal[j].Name = $"Normal {i}";
}
[Benchmark]
public void Cached()
{
for (int i = 0; i < ChangeCount; i++)
for (int j = 0; j < ModelCount; j++)
cached[j].Name = $"Cached {i}";
}
private void EmptyHandler(object sender, PropertyChangedEventArgs args)
{
}
}
public class BaseClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(PropertyChangedEventArgs args)
{
PropertyChanged?.Invoke(this, args);
}
}
public class NormalClass : BaseClass
{
string name;
public string Name
{
get => name;
set
{
if (name == value)
return;
name = value;
OnPropertyChanged(new PropertyChangedEventArgs(nameof(Name)));
}
}
}
public class CachedClass : BaseClass
{
static PropertyChangedEventArgs nameArg = new PropertyChangedEventArgs(nameof(Name));
string name;
public string Name
{
get => name;
set
{
if (name == value)
return;
name = value;
OnPropertyChanged(nameArg);
}
}
}
public class Program
{
public static void Main(string[] args)
{
BenchmarkRunner.Run<PropertyChangedArgBenchmarks>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.