Skip to content

Instantly share code, notes, and snippets.

@svick
Created June 28, 2022 12:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svick/4c8916126154caa43243980720423e2a to your computer and use it in GitHub Desktop.
Save svick/4c8916126154caa43243980720423e2a to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Running;
public class Program
{
static void Main() => BenchmarkRunner.Run<Benchmark>();
}
[MemoryDiagnoser]
public class Benchmark
{
const string Path_CreatedAt = nameof(Path_CreatedAt);
const string Path_UpdatedAt = nameof(Path_UpdatedAt);
const string Type_CreatedAt = nameof(Type_CreatedAt);
const string Type_UpdatedAt = nameof(Type_UpdatedAt);
static readonly DateTime OldCreatedAt = new(2020, 1, 1);
static readonly DateTime OldUpdatedAt = new(2021, 1, 1);
static readonly DateTime NewCreatedAt = new(2022, 1, 1);
static readonly DateTime NewUpdatedAt = new(2023, 1, 1);
ImmutableDictionary<string, DateTime> oldValues = new Dictionary<string, DateTime>
{
{ Path_CreatedAt, OldCreatedAt },
{ Path_UpdatedAt, OldUpdatedAt },
{ Type_CreatedAt, OldCreatedAt },
{ Type_UpdatedAt, OldUpdatedAt }
}.ToImmutableDictionary();
[Benchmark]
public ImmutableDictionary<string, DateTime> OneByOne()
{
return oldValues
.SetItem(Path_CreatedAt, NewCreatedAt)
.SetItem(Path_UpdatedAt, NewUpdatedAt)
.SetItem(Type_CreatedAt, NewCreatedAt)
.SetItem(Type_UpdatedAt, NewUpdatedAt);
}
[Benchmark]
public ImmutableDictionary<string, DateTime> SetItems()
{
return oldValues.SetItems(new KeyValuePair<string, DateTime>[] {
new(Path_CreatedAt, NewCreatedAt),
new(Path_UpdatedAt, NewUpdatedAt),
new(Type_CreatedAt, NewCreatedAt),
new(Type_UpdatedAt, NewUpdatedAt)
});
}
[Benchmark]
public ImmutableDictionary<string, DateTime> ExtensionSetItems()
{
return oldValues.SetItems(
(Path_CreatedAt, NewCreatedAt),
(Path_UpdatedAt, NewUpdatedAt),
(Type_CreatedAt, NewCreatedAt),
(Type_UpdatedAt, NewUpdatedAt)
);
}
}
static class E
{
public static ImmutableDictionary<TKey, TValue> SetItems<TKey, TValue>(
this ImmutableDictionary<TKey, TValue> dictionary, params ValueTuple<TKey, TValue>[] values)
{
var builder = dictionary.ToBuilder();
foreach (var (key, value) in values)
{
builder[key] = value;
}
return builder.ToImmutable();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment