-
-
Notifications
You must be signed in to change notification settings - Fork 54
/
Benchmarks.cs
1409 lines (1127 loc) · 31.1 KB
/
Benchmarks.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using BenchmarkDotNet.Attributes;
using System;
namespace LiveTesting
{
using BenchmarkDotNet.Columns;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Environments;
using BenchmarkDotNet.Exporters;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Loggers;
using BenchmarkDotNet.Mathematics;
using BenchmarkDotNet.Order;
using BenchmarkDotNet.Toolchains.CsProj;
using Ceras;
using Ceras.Formatters;
using MessagePack;
using Newtonsoft.Json;
using ProtoBuf;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
class CerasGlobalBenchmarkConfig : ManualConfig
{
// .With(CsProjClassicNetToolchain.Net472).With(new MonoRuntime("Mono x64", @"C:\Program Files\Mono\bin\mono.exe"))
// .With(CsProjCoreToolchain.NetCoreApp22).With(Runtime.Core));
// .With(CsProjCoreToolchain.NetCoreApp30).With(Runtime.Core));
public static CerasGlobalBenchmarkConfig Short => new CerasGlobalBenchmarkConfig(Job.ShortRun
.With(CsProjCoreToolchain.NetCoreApp22).With(Runtime.Core));
public static CerasGlobalBenchmarkConfig Medium => new CerasGlobalBenchmarkConfig(Job.MediumRun
.With(CsProjCoreToolchain.NetCoreApp22).With(Runtime.Core));
public CerasGlobalBenchmarkConfig(Job baseJob)
{
Orderer = new DefaultOrderer(SummaryOrderPolicy.FastestToSlowest);
baseJob = baseJob
.WithOutlierMode(OutlierMode.OnlyUpper)
.With(Platform.X64)
.WithLaunchCount(1);
Add(baseJob);
Add(HtmlExporter.Default);
Add(BenchmarkLogicalGroupRule.ByCategory);
Add(CategoriesColumn.Default);
Add(TargetMethodColumn.Method);
Add(BaselineRatioColumn.RatioMean);
Add(StatisticColumn.Mean, StatisticColumn.StdErr);
Add(DefaultColumnProviders.Params);
Add(new ConsoleLogger());
}
}
public class Benchmark_SealedTypeOptimization
{
Person1 _personNormal;
Person2 _personSealed;
byte[] _buffer = new byte[0x1000];
CerasSerializer _ceras = new CerasSerializer();
[GlobalSetup]
public void Setup()
{
_personNormal = new Person1 { Age = 5, FirstName = "abc", Reference1 = new Person1(), Reference2 = new Person1() };
_personSealed = new Person2 { Age = 5, FirstName = "abc", Reference1 = new Person2(), Reference2 = new Person2() };
}
[Benchmark(Baseline = true)]
public void Normal()
{
_ceras.Serialize(_personNormal, ref _buffer);
Person1 clone = null;
int offset = 0;
_ceras.Deserialize(ref clone, _buffer, ref offset);
}
[Benchmark()]
public void Sealed()
{
_ceras.Serialize(_personSealed, ref _buffer);
Person2 clone = null;
int offset = 0;
_ceras.Deserialize(ref clone, _buffer, ref offset);
}
public class Person1
{
public int Age { get; set; }
public string FirstName { get; set; }
public Person1 Reference1 { get; set; }
public Person1 Reference2 { get; set; }
}
public sealed class Person2
{
public int Age { get; set; }
public string FirstName { get; set; }
public Person2 Reference1 { get; set; }
public Person2 Reference2 { get; set; }
}
}
// Result: all variations are within the stddev
public class Benchmark_UnsafeCastFuncConstructor
{
Person _person;
Person[] _targetArray;
Func<object> _returnPersonAsObject;
Func<Person> _returnPersonDirectly;
Func<Person> _castedConstructor;
[GlobalSetup]
public void Setup()
{
_returnPersonAsObject = () =>
{
var p = new Person() { FirstName = "a" };
return (object)p;
};
_returnPersonDirectly = () =>
{
var p = new Person() { FirstName = "a" };
return p;
};
_castedConstructor = Unsafe.As<Func<Person>>(_returnPersonAsObject);
_targetArray = new Person[200];
}
[Benchmark(Baseline = true)]
public void MethodDirect()
{
for (int i = 0; i < _targetArray.Length; i++)
_targetArray[i] = _returnPersonDirectly();
}
[Benchmark()]
public void MethodHardCast()
{
for (int i = 0; i < _targetArray.Length; i++)
_targetArray[i] = (Person)_returnPersonAsObject();
}
[Benchmark()]
public void MethodAsCast()
{
for (int i = 0; i < _targetArray.Length; i++)
_targetArray[i] = _returnPersonAsObject() as Person;
}
[Benchmark()]
public void MethodPreCastedDelegate()
{
for (int i = 0; i < _targetArray.Length; i++)
_targetArray[i] = _castedConstructor();
}
[Benchmark()]
public void MethodCastAndCallDelegate()
{
for (int i = 0; i < _targetArray.Length; i++)
_targetArray[i] = Unsafe.As<Func<Person>>(_returnPersonAsObject)();
}
public class Person
{
public int Age { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public SomeEnum SomeEnum { get; set; }
public Person Reference1 { get; set; }
public Person Reference2 { get; set; }
public Person Reference3 { get; set; }
public int[] Numbers { get; set; } = new int[0];
}
public enum SomeEnum : byte
{
Triangle, Cube,
Red, Green, Orange,
SixtyFive,
Cat, Bird, Fish,
Apple, Lemon,
}
}
public class ConstantsInGenericContainerBenchmarks
{
byte[] _buffer = new byte[0x1000];
SerializeDelegate<Person> _serializer1;
SerializeDelegate<Person> _serializer2;
Person _person;
[GlobalSetup]
public void Setup()
{
var ceras = new CerasSerializer();
var parent1 = new Person
{
Age = -901,
FirstName = "Parent 1",
LastName = "abc",
Sex = Sex.Male,
};
var parent2 = new Person
{
Age = 7881964,
FirstName = "Parent 2",
LastName = "xyz",
Sex = Sex.Female,
};
_person = new Person
{
Age = 5,
FirstName = "Riki",
LastName = "Example Person Object",
Sex = Sex.Unknown,
Parent1 = parent1,
Parent2 = parent2,
};
var meta = ceras.GetTypeMetaData(typeof(Person));
var schema = meta.PrimarySchema;
_serializer1 = DynamicFormatter<Person>.GenerateSerializer(ceras, schema, false, false).Compile();
//_serializer2 = DynamicFormatter<Person>.GenerateSerializer2(ceras, schema, false, false);
}
[Benchmark(Baseline = true)]
public void Method1()
{
int offset = 0;
var b = _buffer;
var p = _person;
_serializer1(ref b, ref offset, p);
_serializer1(ref b, ref offset, p);
_serializer1(ref b, ref offset, p);
_serializer1(ref b, ref offset, p);
}
[Benchmark]
public void Method2()
{
int offset = 0;
var b = _buffer;
var p = _person;
_serializer2(ref b, ref offset, p);
_serializer2(ref b, ref offset, p);
_serializer2(ref b, ref offset, p);
_serializer2(ref b, ref offset, p);
}
public class Person
{
public int Age { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Sex Sex { get; set; }
public Person Parent1 { get; set; }
public Person Parent2 { get; set; }
public int[] LuckyNumbers { get; set; } = new int[0];
}
public enum Sex : sbyte
{
Unknown, Male, Female,
}
}
public class MergeBlittingBenchmarks
{
public struct Vector3
{
public float X;
public float Y;
public float Z;
}
// todo: reinterpret formatter
// todo: test if passing the value in Serialize() by ref is faster in single tests, and faster in general
// .. check with bool, int, float, Vector3! But also with strings and larger real-world objects
// todo: some formatter instances may be able to write inline-code, making them much faster!
class Vector3Formatter_MergeBlit_WriteFloat32FixedNoCheck : IFormatter<Vector3>
{
public void Serialize(ref byte[] buffer, ref int offset, Vector3 value)
{
const int v3Size = 3 * 4;
SerializerBinary.EnsureCapacity(ref buffer, offset, v3Size);
var bufferLocal = buffer;
SerializerBinary.WriteFloat32FixedNoCheck(bufferLocal, ref offset, value.X);
SerializerBinary.WriteFloat32FixedNoCheck(bufferLocal, ref offset, value.Y);
SerializerBinary.WriteFloat32FixedNoCheck(bufferLocal, ref offset, value.Z);
}
public void Deserialize(byte[] buffer, ref int offset, ref Vector3 value) => throw new NotImplementedException();
}
class Vector3Formatter_MergeBlit_Fixed : IFormatter<Vector3>
{
public unsafe void Serialize(ref byte[] buffer, ref int offset, Vector3 value)
{
const int v3Size = 3 * 4;
SerializerBinary.EnsureCapacity(ref buffer, offset, v3Size);
var bufferLocal = buffer;
fixed (byte* pBuffer = buffer)
{
var ptr = (float*)(pBuffer + offset);
*ptr = value.X;
ptr++;
*ptr = value.Y;
ptr++;
*ptr = value.Z;
}
offset += v3Size;
}
public void Deserialize(byte[] buffer, ref int offset, ref Vector3 value) => throw new NotImplementedException();
}
class Vector3Formatter_Interface : IFormatter<Vector3>
{
IFormatter<float> _f;
public Vector3Formatter_Interface()
{
_f = new FloatFormatter();
}
public void Serialize(ref byte[] buffer, ref int offset, Vector3 value)
{
_f.Serialize(ref buffer, ref offset, value.X);
_f.Serialize(ref buffer, ref offset, value.Y);
_f.Serialize(ref buffer, ref offset, value.Z);
}
public void Deserialize(byte[] buffer, ref int offset, ref Vector3 value) => throw new NotImplementedException();
}
IFormatter<Vector3>[] _formatterInstances =
{
//new Vector3Formatter_Normal(),
//new Vector3Formatter_MergeBlit1(),
//new Vector3Formatter_MergeBlit2(),
//new Vector3Formatter_MergeBlit3(),
new Vector3Formatter_MergeBlit_WriteFloat32FixedNoCheck(),
new Vector3Formatter_MergeBlit_Fixed(),
new Vector3Formatter_Interface(),
new ReinterpretFormatter<Vector3>(),
};
[Params(0, 1, 2, 3, 4, 5, 6, 7)] // ParamsSource doesn't seem to work at all, must be a bug in benchmarkdotnet
public int TypeIndex { get; set; }
Vector3 _vector3 = new Vector3 { X = -5, Y = 3.121f, Z = 7.2f };
IFormatter<Vector3> _formatter;
byte[] _buffer = new byte[100];
[GlobalSetup]
public void Setup()
{
_formatter = _formatterInstances[TypeIndex];
}
[Benchmark]
public void Test()
{
int offset = 0;
_formatter.Serialize(ref _buffer, ref offset, _vector3);
}
}
public class SerializerComparisonBenchmarks
{
[MessagePackObject]
[ProtoContract]
[Serializable]
public class Person : IEquatable<Person>
{
[Key(0)]
[DataMember]
[ProtoMember(1)]
public virtual int Age { get; set; }
[Key(1)]
[DataMember]
[ProtoMember(2)]
public virtual string FirstName { get; set; }
[Key(2)]
[DataMember]
[ProtoMember(3)]
public virtual string LastName { get; set; }
[Key(3)]
[DataMember]
[ProtoMember(4)]
public virtual Sex Sex { get; set; }
[Key(4)]
[DataMember]
[ProtoMember(5)]
public virtual Person Parent1 { get; set; }
[Key(5)]
[DataMember]
[ProtoMember(6)]
public virtual Person Parent2 { get; set; }
[Key(6)]
[DataMember]
[ProtoMember(7)]
public virtual int[] LuckyNumbers { get; set; } = new int[0];
public override bool Equals(object obj)
{
if (obj is Person other)
return Equals(other);
return false;
}
public bool Equals(Person other)
{
return Age == other.Age
&& FirstName == other.FirstName
&& LastName == other.LastName
&& Sex == other.Sex
&& Equals(Parent1, other.Parent1)
&& Equals(Parent2, other.Parent2)
&& LuckyNumbers.SequenceEqual(other.LuckyNumbers);
}
}
public enum Sex : sbyte
{
Unknown, Male, Female,
}
Person _person;
IList<Person> _list;
static Wire.Serializer _wire;
static NetSerializer.Serializer _netSerializer;
static byte[] _buffer;
static MemoryStream _memStream = new MemoryStream();
static CerasSerializer _ceras;
[GlobalSetup]
public void Setup()
{
//
// Create example data
var parent1 = new Person
{
Age = -901,
FirstName = "Parent 1",
LastName = "abc",
Sex = Sex.Male,
};
var parent2 = new Person
{
Age = 7881964,
FirstName = "Parent 2",
LastName = "xyz",
Sex = Sex.Female,
};
_person = new Person
{
Age = 5,
FirstName = "Riki",
LastName = "Example Person Object",
Sex = Sex.Unknown,
Parent1 = parent1,
Parent2 = parent2,
};
_list = Enumerable.Range(25000, 100).Select(x => new Person { Age = x, FirstName = "a", LastName = "b", Sex = Sex.Female }).ToArray();
//
// Config Serializers
_wire = new Wire.Serializer(new Wire.SerializerOptions(knownTypes: new Type[] { typeof(Person), typeof(Person[]) }));
_netSerializer = new NetSerializer.Serializer(rootTypes: new Type[] { typeof(Person), typeof(Person[]) });
var config = new SerializerConfig();
config.DefaultTargets = TargetMember.AllPublic;
var knownTypes = new[] { typeof(Person), typeof(List<>), typeof(Person[]) };
config.KnownTypes.AddRange(knownTypes);
config.PreserveReferences = false;
_ceras = new CerasSerializer(config);
//
// Run each serializer once to verify they work correctly!
if (!Equals(RunCeras(_person), _person))
ThrowError();
if (!Equals(RunJson(_person), _person))
ThrowError();
if (!Equals(RunMessagePackCSharp(_person), _person))
ThrowError();
if (!Equals(RunProtobuf(_person), _person))
ThrowError();
if (!Equals(RunWire(_person), _person))
ThrowError();
if (!Equals(RunNetSerializer(_person), _person))
ThrowError();
void ThrowError() => throw new InvalidOperationException("Cannot continue with the benchmark because a serializer does not round-trip an object correctly. (Benchmark results will be wrong)");
}
[BenchmarkCategory("Single"), Benchmark]
public void MessagePack_Single() => RunMessagePackCSharp(_person);
[BenchmarkCategory("Single"), Benchmark(Baseline = true)]
public void Ceras_Single() => RunCeras(_person);
//[BenchmarkCategory("Single"), Benchmark]
//public void Protobuf_Single() => RunProtobuf(_person);
//[BenchmarkCategory("Single"), Benchmark]
//public void Wire_Single() => RunWire(_person);
//[BenchmarkCategory("Single"), Benchmark]
//public void NetSerializer_Single() => RunNetSerializer(_person);
//[BenchmarkCategory("List"), Benchmark(Baseline = true)]
//public void Ceras_List() => RunCeras(_list);
//[BenchmarkCategory("List"), Benchmark]
//public void MessagePack_List() => RunMessagePackCSharp(_list);
//[BenchmarkCategory("List"), Benchmark]
//public void Protobuf_List() => RunProtobuf(_list);
//[BenchmarkCategory("List"), Benchmark]
//public void Wire_List() => RunWire(_list);
//[BenchmarkCategory("List"), Benchmark]
//public void NetSerializer_List() => RunNetSerializer(_list);
static T RunCeras<T>(T obj) // Size = 76
{
T clone = default;
int size = _ceras.Serialize(obj, ref _buffer);
_ceras.Deserialize(ref clone, _buffer);
return clone;
}
static T RunMessagePackCSharp<T>(T obj) // Size = 75
{
var data = MessagePackSerializer.Serialize(obj);
var copy = MessagePackSerializer.Deserialize<T>(data);
return copy;
}
static T RunJson<T>(T obj) // Size = 330
{
var data = JsonConvert.SerializeObject(obj);
var clone = JsonConvert.DeserializeObject<T>(data);
return clone;
}
static T RunProtobuf<T>(T obj) // Size = 85
{
_memStream.Position = 0;
ProtoBuf.Serializer.SerializeWithLengthPrefix(_memStream, obj, PrefixStyle.Fixed32);
_memStream.Position = 0;
var clone = ProtoBuf.Serializer.DeserializeWithLengthPrefix<T>(_memStream, PrefixStyle.Fixed32);
return clone;
}
static T RunWire<T>(T obj) // Size = 169
{
_memStream.Position = 0;
_wire.Serialize(obj, _memStream);
_memStream.Position = 0;
var clone = _wire.Deserialize<T>(_memStream);
_memStream.Position = 0;
return clone;
}
static T RunNetSerializer<T>(T obj) // Size = 79
{
_memStream.Position = 0;
_netSerializer.Serialize(_memStream, obj);
_memStream.Position = 0;
_netSerializer.Deserialize(_memStream, out object cloneObj);
var clone = (T)cloneObj;
return clone;
}
}
public class DictionaryBenchmarks
{
List<Type> _allTypes = new List<Type>();
List<Type> _usedTypesA = new List<Type>();
List<Type> _usedTypesB = new List<Type>();
Dictionary<Type, int> _normalDict = new Dictionary<Type, int>();
TypeDictionary<int> _testDict1 = new TypeDictionary<int>();
TypeDictionary2<int> _testDict2 = new TypeDictionary2<int>();
[GlobalSetup]
public void Setup()
{
var allTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(asm => asm.GetTypes());
_allTypes.AddRange(allTypes);
var rng = new Random(123456);
for (int i = 0; i < 80; i++)
{
var index = rng.Next(0, _allTypes.Count);
var t = _allTypes[index];
_usedTypesA.Add(t);
}
for (int i = 0; i < 80; i++)
{
var index = rng.Next(0, _allTypes.Count);
var t = _allTypes[index];
_usedTypesB.Add(t);
}
}
[Benchmark(Baseline = true)]
public void Dictionary()
{
var dict = _normalDict;
// 1. Add all A
for (var i = 0; i < _usedTypesA.Count; i++)
{
var t = _usedTypesA[i];
dict[t] = i;
}
// 2. Test all A and B and sum their values
long sum = 0;
for (var i = 0; i < _usedTypesA.Count; i++)
{
var t = _usedTypesA[i];
if (dict.TryGetValue(t, out int value))
sum += value;
}
for (var i = 0; i < _usedTypesB.Count; i++)
{
var t = _usedTypesB[i];
if (dict.TryGetValue(t, out int value))
sum += value;
}
}
[Benchmark]
public void NewDictionary()
{
var dict = _testDict1;
// 1. Add all A
for (var i = 0; i < _usedTypesA.Count; i++)
{
var t = _usedTypesA[i];
ref var entry = ref dict.GetOrAddValueRef(t);
entry = i;
}
// 2. Test all A and B and sum their values
long sum = 0;
for (var i = 0; i < _usedTypesA.Count; i++)
{
var t = _usedTypesA[i];
if (dict.TryGetValue(t, out int value))
sum += value;
}
for (var i = 0; i < _usedTypesB.Count; i++)
{
var t = _usedTypesB[i];
if (dict.TryGetValue(t, out int value))
sum += value;
}
}
[Benchmark]
public void NewDictionary2()
{
var dict = _testDict2;
// 1. Add all A
for (var i = 0; i < _usedTypesA.Count; i++)
{
var t = _usedTypesA[i];
ref var entry = ref dict.GetOrAddValueRef(t);
entry = i;
}
// 2. Test all A and B and sum their values
long sum = 0;
for (var i = 0; i < _usedTypesA.Count; i++)
{
var t = _usedTypesA[i];
if (dict.TryGetValue(t, out int value))
sum += value;
}
for (var i = 0; i < _usedTypesB.Count; i++)
{
var t = _usedTypesB[i];
if (dict.TryGetValue(t, out int value))
sum += value;
}
}
}
public class CreateBenchmarks
{
List<Type> _createdTypes = new List<Type>();
[GlobalSetup]
public void Setup()
{
_createdTypes.Add(typeof(List<int>));
_createdTypes.Add(typeof(List<bool>));
_createdTypes.Add(typeof(List<DateTime>));
_createdTypes.Add(typeof(MemoryStream));
_createdTypes.Add(typeof(Person));
}
[Benchmark(Baseline = true)]
public void Activator()
{
for (int i = 0; i < _createdTypes.Count; i++)
{
var t = _createdTypes[i];
System.Activator.CreateInstance(t);
}
}
[Benchmark]
public void CreateMethod()
{
for (int i = 0; i < _createdTypes.Count; i++)
{
var t = _createdTypes[i];
var ctor = CreateCtor(t);
ctor();
}
}
[Benchmark]
public void CreateExprTree()
{
for (int i = 0; i < _createdTypes.Count; i++)
{
var t = _createdTypes[i];
var ctor = CreateExpressionTree(t);
ctor();
}
}
public static Func<object> CreateCtor(Type type)
{
if (type == null)
throw new NullReferenceException("type");
ConstructorInfo emptyConstructor = type.GetConstructor(Type.EmptyTypes);
if (emptyConstructor == null)
throw new NullReferenceException("cannot find a parameterless constructor for " + type.FullName);
var dynamicMethod = new DynamicMethod("CreateInstance", type, Type.EmptyTypes, true);
ILGenerator ilGenerator = dynamicMethod.GetILGenerator();
ilGenerator.Emit(OpCodes.Nop);
ilGenerator.Emit(OpCodes.Newobj, emptyConstructor);
ilGenerator.Emit(OpCodes.Ret);
return (Func<object>)dynamicMethod.CreateDelegate(typeof(Func<object>));
}
public static Func<object> CreateExpressionTree(Type type)
{
if (type == null)
throw new NullReferenceException("type");
ConstructorInfo emptyConstructor = type.GetConstructor(Type.EmptyTypes);
if (emptyConstructor == null)
throw new NullReferenceException("cannot find a parameterless constructor for " + type.FullName);
var newExp = Expression.New(emptyConstructor);
var lambda = Expression.Lambda<Func<object>>(newExp);
return lambda.Compile();
}
}
public class PrimitiveBenchmarks
{
int _someBaseNumber;
Action _empty1;
Action _empty2;
static readonly Type _iTupleInterface = typeof(Tuple<>).GetInterfaces().First(t => t.Name == "ITuple");
Type[] _types;
[GlobalSetup]
public void Setup()
{
_someBaseNumber = Environment.TickCount;
_empty1 = () => { };
_empty2 = Expression.Lambda<Action>(Expression.Empty()).Compile();
_types = new Type[] { typeof(Nullable<int>), typeof(Tuple<int, int, int, int, int, int, int, int>), typeof(Tuple<int, int>), typeof(Nullable<ByteEnum>), typeof(Tuple<string>), };
}
[BenchmarkCategory("All", "Int")]
[Benchmark(Baseline = true)]
[MethodImpl(MethodImplOptions.NoOptimization)]
public void IntegerIncrement()
{
var x = _someBaseNumber;
x = x + 1;
x = x + 1;
x = x + 1;
x = x + 1;
}
[BenchmarkCategory("All", "Int")]
[Benchmark]
public void FieldIncrement()
{
_someBaseNumber++;
_someBaseNumber++;
_someBaseNumber++;
_someBaseNumber++;
}
[BenchmarkCategory("All", "Action")]
[Benchmark(Baseline = true)]
public void EmptyAction4x()
{
_empty1();
_empty1();
_empty1();
_empty1();
}
[BenchmarkCategory("All", "Action")]
[Benchmark]
public void EmptyExpression4x()
{
_empty2();
_empty2();
_empty2();
_empty2();
}
[BenchmarkCategory("All", "Action")]
[Benchmark]
public void EmptyAction4xCached()
{
var e = _empty1;
e();
e();
e();
e();
}
[BenchmarkCategory("All", "Action")]
[Benchmark]
public void EmptyExpression4xCache()
{
var e = _empty2;
e();
e();
e();
e();
}
[BenchmarkCategory("All", "TypeCheck")]
[Benchmark(Baseline = true)]
public void CheckTypeByGenericTypeDef()
{
var types = _types;
int tuplesFound = 0;
for (int i = 0; i < types.Length; i++)
{
var t = types[i];
if (t.IsGenericType)
{
var genericDef = t.GetGenericTypeDefinition();
if (genericDef == typeof(Tuple<>) ||
genericDef == typeof(Tuple<,>) ||
genericDef == typeof(Tuple<,,>) ||
genericDef == typeof(Tuple<,,,>) ||
genericDef == typeof(Tuple<,,,,>) ||
genericDef == typeof(Tuple<,,,,,>) ||
genericDef == typeof(Tuple<,,,,,,>) ||
genericDef == typeof(Tuple<,,,,,,,>))
tuplesFound++;
}
}
}
[BenchmarkCategory("All", "TypeCheck")]
[Benchmark]
public void CheckTypeByName()
{
var types = _types;
int tuplesFound = 0;