summaryrefslogtreecommitdiff
path: root/tests/src/JIT/Performance/CodeQuality/Span/SpanBench.cs
blob: ef694421ef3e0567f8e8dad18bf0d032c2e961c5 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using Xunit;
using Microsoft.Xunit.Performance;

[assembly: OptimizeForBenchmarks]

namespace Span
{
    public class SpanBench
    {

#if DEBUG
        const int BubbleSortIterations = 1;
        const int QuickSortIterations = 1;
        const int FillAllIterations = 1;
        const int BaseIterations = 1;
#else
        // Appropriately-scaled iteration counts for the various benchmarks
        const int BubbleSortIterations = 100;
        const int QuickSortIterations = 1000;
        const int FillAllIterations = 100000;
        const int BaseIterations = 10000000;
#endif

        // Default length for arrays of mock input data
        const int DefaultLength = 1024;

        // Helpers
        #region Helpers
        [StructLayout(LayoutKind.Sequential)]
        private sealed class TestClass<T>
        {
            private double _d;
            public T[] C0;
        }

        // Copying the result of a computation to Sink<T>.Instance is a way
        // to prevent the jit from considering the computation dead and removing it.
        private sealed class Sink<T>
        {
            public T Data;
            public static Sink<T> Instance = new Sink<T>();
        }

        // Use statics to smuggle some information from Main to Invoke when running tests
        // from the command line.
        static bool IsXunitInvocation = true; // xunit-perf leaves this true; command line Main sets to false
        static int CommandLineInnerIterationCount = 0;   // used to communicate iteration count from BenchmarkAttribute
                                                         // (xunit-perf exposes the same in static property Benchmark.InnerIterationCount)
        static bool DoWarmUp; // Main sets this when calling a new benchmark routine


        // Invoke routine to abstract away the difference between running under xunit-perf vs running from the
        // command line.  Inner loop to be measured is taken as an Action<int>, and invoked passing the number
        // of iterations that the inner loop should execute.
        static void Invoke(Action<int> innerLoop, string nameFormat, params object[] nameArgs)
        {
            if (IsXunitInvocation)
            {
                foreach (var iteration in Benchmark.Iterations)
                    using (iteration.StartMeasurement())
                        innerLoop((int)Benchmark.InnerIterationCount);
            }
            else
            {
                if (DoWarmUp)
                {
                    // Run some warm-up iterations before measuring
                    innerLoop(CommandLineInnerIterationCount);
                    // Clear the flag since we're now warmed up (caller will
                    // reset it before calling new code)
                    DoWarmUp = false;
                }

                // Now do the timed run of the inner loop.
                Stopwatch sw = Stopwatch.StartNew();
                innerLoop(CommandLineInnerIterationCount);
                sw.Stop();

                // Print result.
                string name = String.Format(nameFormat, nameArgs);
                double timeInMs = sw.Elapsed.TotalMilliseconds;
                Console.WriteLine("{0}: {1}ms", name, timeInMs);
            }
        }

        // Helper for the sort tests to get some pseudo-random input
        static int[] GetUnsortedData(int length)
        {
            int[] unsortedData = new int[length];
            Random r = new Random(42);
            for (int i = 0; i < unsortedData.Length; ++i)
            {
                unsortedData[i] = r.Next();
            }
            return unsortedData;
        }
        #endregion // helpers

        // Tests that implement some vary basic algorithms (fill/sort) over spans and arrays
        #region Algorithm tests

        #region TestFillAllSpan
        [Benchmark(InnerIterationCount = FillAllIterations)]
        [InlineData(DefaultLength)]
        public static void FillAllSpan(int length)
        {
            byte[] a = new byte[length];

            Invoke((int innerIterationCount) =>
            {
                Span<byte> s = new Span<byte>(a);
                for (int i = 0; i < innerIterationCount; ++i)
                {
                    TestFillAllSpan(s);
                }
            },
            "TestFillAllSpan({0})", length);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        static void TestFillAllSpan(Span<byte> span)
        {
            for (int i = 0; i < span.Length; ++i)
            {
                span[i] = unchecked((byte)i);
            }
        }
        #endregion

        #region TestFillAllArray
        [Benchmark(InnerIterationCount = FillAllIterations)]
        [InlineData(DefaultLength)]
        public static void FillAllArray(int length)
        {
            byte[] a = new byte[length];

            Invoke((int innerIterationCount) =>
            {
                for (int i = 0; i < innerIterationCount; ++i)
                {
                    TestFillAllArray(a);
                }
            },
            "TestFillArray({0})", length);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        static void TestFillAllArray(byte[] data)
        {
            for (int i = 0; i < data.Length; ++i)
            {
                data[i] = unchecked((byte)i);
            }
        }
        #endregion

        #region TestFillAllReverseSpan
        [Benchmark(InnerIterationCount = FillAllIterations)]
        [InlineData(DefaultLength)]
        public static void FillAllReverseSpan(int length)
        {
            byte[] a = new byte[length];

            Invoke((int innerIterationCount) =>
            {
                Span<byte> s = new Span<byte>(a);
                for (int i = 0; i < innerIterationCount; ++i)
                {
                    TestFillAllReverseSpan(s);
                }
            },
            "TestFillAllReverseSpan({0})", length);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        static void TestFillAllReverseSpan(Span<byte> span)
        {
            for (int i = span.Length; --i >= 0;)
            {
                span[i] = unchecked((byte)i);
            }
        }
        #endregion

        #region TestFillAllReverseArray
        [Benchmark(InnerIterationCount = FillAllIterations)]
        [InlineData(DefaultLength)]
        public static void FillAllReverseArray(int length)
        {
            byte[] a = new byte[length];

            Invoke((int innerIterationCount) =>
            {
                for (int i = 0; i < innerIterationCount; ++i)
                {
                    TestFillAllReverseArray(a);
                }
            },
            "TestFillAllReverseArray({0})", length);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        static void TestFillAllReverseArray(byte[] data)
        {
            for (int i = data.Length; --i >= 0;)
            {
                data[i] = unchecked((byte)i);
            }
        }
        #endregion

        #region TestQuickSortSpan
        [Benchmark(InnerIterationCount = QuickSortIterations)]
        [InlineData(DefaultLength)]
        public static void QuickSortSpan(int length)
        {
            int[] data = new int[length];
            int[] unsortedData = GetUnsortedData(length);

            Invoke((int innerIterationCount) =>
            {
                Span<int> span = new Span<int>(data);

                for (int i = 0; i < innerIterationCount; ++i)
                {
                    Array.Copy(unsortedData, data, length);
                    TestQuickSortSpan(span);
                }
            },
            "TestQuickSortSpan({0})", length);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        static void TestQuickSortSpan(Span<int> data)
        {
            if (data.Length <= 1)
            {
                return;
            }

            int lo = 0;
            int hi = data.Length - 1;
            int i, j;
            int pivot, temp;
            for (i = lo, j = hi, pivot = data[hi]; i < j;)
            {
                while (i < j && data[i] <= pivot)
                {
                    ++i;
                }
                while (j > i && data[j] >= pivot)
                {
                    --j;
                }
                if (i < j)
                {
                    temp = data[i];
                    data[i] = data[j];
                    data[j] = temp;
                }
            }
            if (i != hi)
            {
                temp = data[i];
                data[i] = pivot;
                data[hi] = temp;
            }

            TestQuickSortSpan(data.Slice(0, i));
            TestQuickSortSpan(data.Slice(i + 1));
        }
        #endregion

        #region TestBubbleSortSpan
        [Benchmark(InnerIterationCount = BubbleSortIterations)]
        [InlineData(DefaultLength)]
        public static void BubbleSortSpan(int length)
        {
            int[] data = new int[length];
            int[] unsortedData = GetUnsortedData(length);

            Invoke((int innerIterationCount) =>
            {
                Span<int> span = new Span<int>(data);

                for (int i = 0; i < innerIterationCount; i++)
                {
                    Array.Copy(unsortedData, data, length);
                    TestBubbleSortSpan(span);
                }
            },
            "TestBubbleSortSpan({0})", length);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        static void TestBubbleSortSpan(Span<int> span)
        {
            bool swap;
            int temp;
            int n = span.Length - 1;
            do
            {
                swap = false;
                for (int i = 0; i < n; i++)
                {
                    if (span[i] > span[i + 1])
                    {
                        temp = span[i];
                        span[i] = span[i + 1];
                        span[i + 1] = temp;
                        swap = true;
                    }
                }
                --n;
            }
            while (swap);
        }
        #endregion

        #region TestQuickSortArray
        [Benchmark(InnerIterationCount = QuickSortIterations)]
        [InlineData(DefaultLength)]
        public static void QuickSortArray(int length)
        {
            int[] data = new int[length];
            int[] unsortedData = GetUnsortedData(length);

            Invoke((int innerIterationCount) =>
            {
                for (int i = 0; i < innerIterationCount; i++)
                {
                    Array.Copy(unsortedData, data, length);
                    TestQuickSortArray(data, 0, data.Length - 1);
                }
            },
            "TestQuickSortArray({0})", length);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        static void TestQuickSortArray(int[] data, int lo, int hi)
        {
            if (lo >= hi)
            {
                return;
            }

            int i, j;
            int pivot, temp;
            for (i = lo, j = hi, pivot = data[hi]; i < j;)
            {
                while (i < j && data[i] <= pivot)
                {
                    ++i;
                }
                while (j > i && data[j] >= pivot)
                {
                    --j;
                }
                if (i < j)
                {
                    temp = data[i];
                    data[i] = data[j];
                    data[j] = temp;
                }
            }
            if (i != hi)
            {
                temp = data[i];
                data[i] = pivot;
                data[hi] = temp;
            }

            TestQuickSortArray(data, lo, i - 1);
            TestQuickSortArray(data, i + 1, hi);
        }
        #endregion

        #region TestBubbleSortArray
        [Benchmark(InnerIterationCount = BubbleSortIterations)]
        [InlineData(DefaultLength)]
        public static void BubbleSortArray(int length)
        {
            int[] data = new int[length];
            int[] unsortedData = GetUnsortedData(length);

            Invoke((int innerIterationCount) =>
            {
                for (int i = 0; i < innerIterationCount; i++)
                {
                    Array.Copy(unsortedData, data, length);
                    TestBubbleSortArray(data);
                }
            },
            "TestBubbleSortArray({0})", length);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        static void TestBubbleSortArray(int[] data)
        {
            bool swap;
            int temp;
            int n = data.Length - 1;
            do
            {
                swap = false;
                for (int i = 0; i < n; i++)
                {
                    if (data[i] > data[i + 1])
                    {
                        temp = data[i];
                        data[i] = data[i + 1];
                        data[i + 1] = temp;
                        swap = true;
                    }
                }
                --n;
            }
            while (swap);
        }
        #endregion

        #endregion // Algorithm tests

        // TestSpanAPIs (For comparison with Array and Slow Span)
        #region TestSpanAPIs

        #region TestSpanConstructor<T>
        [Benchmark(InnerIterationCount = BaseIterations)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestSpanConstructorByte(int length)
        {
            InvokeTestSpanConstructor<byte>(length);
        }

        [Benchmark(InnerIterationCount = BaseIterations / 100)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestSpanConstructorString(int length)
        {
            InvokeTestSpanConstructor<string>(length);
        }

        static void InvokeTestSpanConstructor<T>(int length)
        {
            var array = new T[length];

            Invoke((int innerIterationCount) => TestSpanConstructor<T>(array, innerIterationCount, false),
                "TestSpanConstructor<{0}>({1})", typeof(T).Name, length);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        static void TestSpanConstructor<T>(T[] array, int iterationCount, bool untrue)
        {
            var sink = Sink<T>.Instance;

            for (int i = 0; i < iterationCount; i++)
            {
                var span = new Span<T>(array);
                // Under a condition that we know is false but the jit doesn't,
                // add a read from 'span' to make sure it's not dead, and an assignment
                // to 'array' so the constructor call won't get hoisted.
                if (untrue) { sink.Data = span[0]; array = new T[iterationCount]; }
            }
        }
        #endregion

        #region TestSpanDangerousCreate<T>
        [Benchmark(InnerIterationCount = BaseIterations)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestSpanDangerousCreateByte(int length)
        {
            InvokeTestSpanDangerousCreate<byte>(length);
        }

        [Benchmark(InnerIterationCount = BaseIterations)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestSpanDangerousCreateString(int length)
        {
            InvokeTestSpanDangerousCreate<string>(length);
        }

        static void InvokeTestSpanDangerousCreate<T>(int length)
        {
            TestClass<T> testClass = new TestClass<T>();
            testClass.C0 = new T[length];

            Invoke((int innerIterationCount) => TestSpanDangerousCreate<T>(testClass, innerIterationCount, false),
                "TestSpanDangerousCreate<{0}>({1})", typeof(T).Name, length);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        static void TestSpanDangerousCreate<T>(TestClass<T> testClass, int iterationCount, bool untrue)
        {
            var sink = Sink<T>.Instance;

            for (int i = 0; i < iterationCount; i++)
            {
                var span = Span<T>.DangerousCreate(testClass, ref testClass.C0[0], testClass.C0.Length);
                // Under a condition that we know is false but the jit doesn't,
                // add a read from 'span' to make sure it's not dead, and an assignment
                // to 'testClass' so the DangerousCreate call won't get hoisted.
                if (untrue) { sink.Data = span[0]; testClass = new TestClass<T>(); }
            }
        }
        #endregion

        #region TestSpanDangerousGetPinnableReference<T>
        [Benchmark(InnerIterationCount = BaseIterations)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestSpanDangerousGetPinnableReferenceByte(int length)
        {
            InvokeTestSpanDangerousGetPinnableReference<byte>(length);
        }

        [Benchmark(InnerIterationCount = BaseIterations)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestSpanDangerousGetPinnableReferenceString(int length)
        {
            InvokeTestSpanDangerousGetPinnableReference<string>(length);
        }

        static void InvokeTestSpanDangerousGetPinnableReference<T>(int length)
        {
            var array = new T[length];

            Invoke((int innerIterationCount) => TestSpanDangerousGetPinnableReference<T>(array, innerIterationCount),
                "TestSpanDangerousGetPinnableReference<{0}>({1})", typeof(T).Name, length);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        static void TestSpanDangerousGetPinnableReference<T>(T[] array, int iterationCount)
        {
            var sink = Sink<T>.Instance;
            var span = new Span<T>(array);

            for (int i = 0; i < iterationCount; i++)
            {
                ref T temp = ref span.DangerousGetPinnableReference();
                sink.Data = temp;
            }
        }
        #endregion

        #region TestSpanIndexHoistable<T>
        [Benchmark(InnerIterationCount = BaseIterations)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestSpanIndexHoistableByte(int length)
        {
            InvokeTestSpanIndexHoistable<byte>(length);
        }

        [Benchmark(InnerIterationCount = BaseIterations)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestSpanIndexHoistableString(int length)
        {
            InvokeTestSpanIndexHoistable<string>(length);
        }

        static void InvokeTestSpanIndexHoistable<T>(int length)
        {
            var array = new T[length];

            Invoke((int innerIterationCount) => TestSpanIndexHoistable<T>(array, length, innerIterationCount),
                "TestSpanIndexHoistable<{0}>({1})", typeof(T).Name, length);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        static void TestSpanIndexHoistable<T>(T[] array, int length, int iterationCount)
        {
            var sink = Sink<T>.Instance;
            var span = new Span<T>(array);

            for (int i = 0; i < iterationCount; i++)
                    sink.Data = span[length/2];
        }
        #endregion

        #region TestArrayIndexHoistable<T>
        [Benchmark(InnerIterationCount = BaseIterations)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestArrayIndexHoistableByte(int length)
        {
            InvokeTestArrayIndexHoistable<byte>(length);
        }

        [Benchmark(InnerIterationCount = BaseIterations)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestArrayIndexHoistableString(int length)
        {
            InvokeTestArrayIndexHoistable<string>(length);
        }

        static void InvokeTestArrayIndexHoistable<T>(int length)
        {
            var array = new T[length];
            Invoke((int innerIterationCount) => TestArrayIndexHoistable<T>(array, length, innerIterationCount),
                "TestArrayIndexHoistable<{0}>({1})", typeof(T).Name, length);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        static void TestArrayIndexHoistable<T>(T[] array, int length, int iterationCount)
        {
            var sink = Sink<T>.Instance;

            for (int i = 0; i < iterationCount; i++)
                sink.Data = array[length / 2];
        }
        #endregion

        #region TestSpanIndexVariant<T>
        [Benchmark(InnerIterationCount = BaseIterations)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestSpanIndexVariantByte(int length)
        {
            InvokeTestSpanIndexVariant<byte>(length);
        }

        [Benchmark(InnerIterationCount = BaseIterations)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestSpanIndexVariantString(int length)
        {
            InvokeTestSpanIndexVariant<string>(length);
        }

        static void InvokeTestSpanIndexVariant<T>(int length)
        {
            var array = new T[length];

            Invoke((int innerIterationCount) => TestSpanIndexVariant<T>(array, length, innerIterationCount),
                "TestSpanIndexVariant<{0}>({1})", typeof(T).Name, length);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        static void TestSpanIndexVariant<T>(T[] array, int length, int iterationCount)
        {
            var sink = Sink<T>.Instance;
            var span = new Span<T>(array);
            int mask = (length < 2 ? 0 : (length < 8 ? 1 : 7));

            for (int i = 0; i < iterationCount; i++)
                sink.Data = span[i & mask];
        }
        #endregion

        #region TestArrayIndexVariant<T>
        [Benchmark(InnerIterationCount = BaseIterations)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestArrayIndexVariantByte(int length)
        {
            InvokeTestArrayIndexVariant<byte>(length);
        }

        [Benchmark(InnerIterationCount = BaseIterations)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestArrayIndexVariantString(int length)
        {
            InvokeTestArrayIndexVariant<string>(length);
        }

        static void InvokeTestArrayIndexVariant<T>(int length)
        {
            var array = new T[length];

            Invoke((int innerIterationCount) => TestArrayIndexVariant<T>(array, length, innerIterationCount),
                "TestArrayIndexVariant<{0}>({1})", typeof(T).Name, length);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        static void TestArrayIndexVariant<T>(T[] array, int length, int iterationCount)
        {
            var sink = Sink<T>.Instance;
            int mask = (length < 2 ? 0 : (length < 8 ? 1 : 7));

            for (int i = 0; i < iterationCount; i++)
            {
                sink.Data = array[i & mask];
            }
        }
        #endregion

        #region TestSpanSlice<T>
        [Benchmark(InnerIterationCount = BaseIterations)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestSpanSliceByte(int length)
        {
            InvokeTestSpanSlice<byte>(length);
        }

        [Benchmark(InnerIterationCount = BaseIterations)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestSpanSliceString(int length)
        {
            InvokeTestSpanSlice<string>(length);
        }

        static void InvokeTestSpanSlice<T>(int length)
        {
            var array = new T[length];

            Invoke((int innerIterationCount) => TestSpanSlice<T>(array, length, innerIterationCount, false),
                "TestSpanSlice<{0}>({1})", typeof(T).Name, length);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        static void TestSpanSlice<T>(T[] array, int length, int iterationCount, bool untrue)
        {
            var span = new Span<T>(array);
            var sink = Sink<T>.Instance;

            for (int i = 0; i < iterationCount; i++)
            {
                var slice = span.Slice(length / 2);
                // Under a condition that we know is false but the jit doesn't,
                // add a read from 'span' to make sure it's not dead, and an assignment
                // to 'array' so the slice call won't get hoisted.
                if (untrue) { sink.Data = slice[0]; array = new T[iterationCount]; }
            }
        }
        #endregion

        #region TestSpanToArray<T>
        [Benchmark(InnerIterationCount = BaseIterations / 100)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestSpanToArrayByte(int length)
        {
            InvokeTestSpanToArray<byte>(length);
        }

        [Benchmark(InnerIterationCount = BaseIterations / 100)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestSpanToArrayString(int length)
        {
            InvokeTestSpanToArray<string>(length);
        }

        static void InvokeTestSpanToArray<T>(int length)
        {
            var array = new T[length];

            Invoke((int innerIterationCount) => TestSpanToArray<T>(array, length, innerIterationCount),
                "TestSpanToArray<{0}>({1})", typeof(T).Name, length);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        static void TestSpanToArray<T>(T[] array, int length, int iterationCount)
        {
            var span = new Span<T>(array);
            var sink = Sink<T[]>.Instance;

            for (int i = 0; i < iterationCount; i++)
                sink.Data = span.ToArray();
        }
        #endregion

        #region TestSpanCopyTo<T>
        [Benchmark(InnerIterationCount = BaseIterations / 10)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestSpanCopyToByte(int length)
        {
            InvokeTestSpanCopyTo<byte>(length);
        }

        [Benchmark(InnerIterationCount = BaseIterations / 100)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestSpanCopyToString(int length)
        {
            InvokeTestSpanCopyTo<string>(length);
        }

        static void InvokeTestSpanCopyTo<T>(int length)
        {
            var array = new T[length];
            var destArray = new T[array.Length];

            Invoke((int innerIterationCount) => TestSpanCopyTo<T>(array, destArray, innerIterationCount),
                "TestSpanCopyTo<{0}>({1})", typeof(T).Name, length);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        static void TestSpanCopyTo<T>(T[] array, T[] destArray, int iterationCount)
        {
            var span = new Span<T>(array);
            var destination = new Span<T>(destArray);

            for (int i = 0; i < iterationCount; i++)
                span.CopyTo(destination);
        }
        #endregion

        #region TestArrayCopyTo<T>
        [Benchmark(InnerIterationCount = BaseIterations / 10)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestArrayCopyToByte(int length)
        {
            InvokeTestArrayCopyTo<byte>(length);
        }

        [Benchmark(InnerIterationCount = BaseIterations / 100)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestArrayCopyToString(int length)
        {
            InvokeTestArrayCopyTo<string>(length);
        }

        static void InvokeTestArrayCopyTo<T>(int length)
        {
            var array = new T[length];
            var destination = new T[array.Length];

            Invoke((int innerIterationCount) => TestArrayCopyTo<T>(array, destination, innerIterationCount),
                "TestArrayCopyTo<{0}>({1})", typeof(T).Name, length);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        static void TestArrayCopyTo<T>(T[] array, T[] destination, int iterationCount)
        {
            for (int i = 0; i < iterationCount; i++)
                array.CopyTo(destination, 0);
        }
        #endregion

        #region TestSpanFill<T>
        [Benchmark(InnerIterationCount = BaseIterations * 10)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestSpanFillByte(int length)
        {
            InvokeTestSpanFill<byte>(length);
        }

        [Benchmark(InnerIterationCount = BaseIterations / 100)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestSpanFillString(int length)
        {
            InvokeTestSpanFill<string>(length);
        }

        static void InvokeTestSpanFill<T>(int length)
        {
            var array = new T[length];

            Invoke((int innerIterationCount) => TestSpanFill<T>(array, innerIterationCount),
                "TestSpanFill<{0}>({1})", typeof(T).Name, length);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        static void TestSpanFill<T>(T[] array, int iterationCount)
        {
            var span = new Span<T>(array);
            for (int i = 0; i < iterationCount; i++)
                span.Fill(default(T));
        }
        #endregion

        #region TestSpanClear<T>
        [Benchmark(InnerIterationCount = BaseIterations / 10)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestSpanClearByte(int length)
        {
            InvokeTestSpanClear<byte>(length);
        }

        [Benchmark(InnerIterationCount = BaseIterations / 10)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestSpanClearString(int length)
        {
            InvokeTestSpanClear<string>(length);
        }

        static void InvokeTestSpanClear<T>(int length)
        {
            var array = new T[length];

            Invoke((int innerIterationCount) => TestSpanClear<T>(array, innerIterationCount),
                "TestSpanClear<{0}>({1})", typeof(T).Name, length);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        static void TestSpanClear<T>(T[] array, int iterationCount)
        {
            var span = new Span<T>(array);
            for (int i = 0; i < iterationCount; i++)
                span.Clear();
        }
        #endregion

        #region TestArrayClear<T>
        [Benchmark(InnerIterationCount = BaseIterations / 10)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestArrayClearByte(int length)
        {
            InvokeTestArrayClear<byte>(length);
        }

        [Benchmark(InnerIterationCount = BaseIterations / 10)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestArrayClearString(int length)
        {
            InvokeTestArrayClear<string>(length);
        }

        static void InvokeTestArrayClear<T>(int length)
        {
            var array = new T[length];

            Invoke((int innerIterationCount) => TestArrayClear<T>(array, length, innerIterationCount),
                "TestArrayClear<{0}>({1})", typeof(T).Name, length);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        static void TestArrayClear<T>(T[] array, int length, int iterationCount)
        {
            for (int i = 0; i < iterationCount; i++)
                Array.Clear(array, 0, length);
        }
        #endregion

        #region TestSpanAsBytes<T>
        [Benchmark(InnerIterationCount = BaseIterations)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestSpanAsBytesByte(int length)
        {
            InvokeTestSpanAsBytes<byte>(length);
        }

        [Benchmark(InnerIterationCount = BaseIterations)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestSpanAsBytesInt(int length)
        {
            InvokeTestSpanAsBytes<int>(length);
        }

        static void InvokeTestSpanAsBytes<T>(int length)
            where T : struct
        {
            var array = new T[length];

            Invoke((int innerIterationCount) => TestSpanAsBytes<T>(array, innerIterationCount, false),
                "TestSpanAsBytes<{0}>({1})", typeof(T).Name, length);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        static void TestSpanAsBytes<T>(T[] array, int iterationCount, bool untrue)
            where T : struct
        {
            var sink = Sink<byte>.Instance;
            var span = new Span<T>(array);

            for (int i = 0; i < iterationCount; i++)
            {
                var byteSpan = span.AsBytes();
                // Under a condition that we know is false but the jit doesn't,
                // add a read from 'byteSpan' to make sure it's not dead, and an assignment
                // to 'span' so the AsBytes call won't get hoisted.
                if (untrue) { sink.Data = byteSpan[0]; span = new Span<T>(); }
            }
        }
        #endregion

        #region TestSpanNonPortableCast<T>
        [Benchmark(InnerIterationCount = BaseIterations)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestSpanNonPortableCastFromByteToInt(int length)
        {
            InvokeTestSpanNonPortableCast<byte, int>(length);
        }

        [Benchmark(InnerIterationCount = BaseIterations)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestSpanNonPortableCastFromIntToByte(int length)
        {
            InvokeTestSpanNonPortableCast<int, byte>(length);
        }

        static void InvokeTestSpanNonPortableCast<From, To>(int length)
            where From : struct
            where To : struct
        {
            var array = new From[length];

            Invoke((int innerIterationCount) => TestSpanNonPortableCast<From, To>(array, innerIterationCount, false),
                "TestSpanNonPortableCast<{0}, {1}>({2})", typeof(From).Name, typeof(To).Name, length);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        static void TestSpanNonPortableCast<From, To>(From[] array, int iterationCount, bool untrue)
            where From : struct
            where To : struct
        {
            var sink = Sink<To>.Instance;
            var span = new Span<From>(array);

            for (int i = 0; i < iterationCount; i++)
            {
                var toSpan = span.NonPortableCast<From, To>();
                // Under a condition that we know is false but the jit doesn't,
                // add a read from 'toSpan' to make sure it's not dead, and an assignment
                // to 'span' so the AsBytes call won't get hoisted.
                if (untrue) { sink.Data = toSpan[0]; span = new Span<From>(); }
            }
        }
        #endregion

        #region TestSpanAsSpanStringChar<T>

        [Benchmark(InnerIterationCount = BaseIterations)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public static void TestSpanAsSpanStringCharWrapper(int length)
        {
            StringBuilder sb = new StringBuilder();
            Random rand = new Random(42);
            char[] c = new char[1];
            for (int i = 0; i < length; i++)
            {
                c[0] = (char)rand.Next(32, 126);
                sb.Append(new string(c));
            }
            string s = sb.ToString();

            Invoke((int innerIterationCount) => TestSpanAsSpanStringChar(s, innerIterationCount, false),
                "TestSpanAsSpanStringChar({0})", length);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        static void TestSpanAsSpanStringChar(string s, int iterationCount, bool untrue)
        {
            var sink = Sink<char>.Instance;

            for (int i = 0; i < iterationCount; i++)
            {
                var charSpan = s.AsSpan();
                // Under a condition that we know is false but the jit doesn't,
                // add a read from 'charSpan' to make sure it's not dead, and an assignment
                // to 's' so the AsBytes call won't get hoisted.
                if (untrue) { sink.Data = charSpan[0]; s = "block hoisting the call to AsSpan()"; }
            }
        }

        #endregion

        #endregion // TestSpanAPIs


        public static int Main(string[] args)
        {
            // When we call into Invoke, it'll need to know this isn't xunit-perf running
            IsXunitInvocation = false;

            // Now simulate xunit-perf's benchmark discovery so we know what tests to invoke
            TypeInfo t = typeof(SpanBench).GetTypeInfo();
            foreach(MethodInfo m in t.DeclaredMethods)
            {
                BenchmarkAttribute benchAttr = m.GetCustomAttribute<BenchmarkAttribute>();
                if (benchAttr != null)
                {
                    // All benchmark methods in this test set the InnerIterationCount on their BenchmarkAttribute.
                    // Take max of specified count and 1 since some tests use expressions for their count that
                    // evaluate to 0 under DEBUG.
                    CommandLineInnerIterationCount = Math.Max((int)benchAttr.InnerIterationCount, 1);

                    // Request a warm-up iteration before measuring this benchmark method.
                    DoWarmUp = true;

                    // Get the benchmark to measure as a delegate taking the number of inner-loop iterations to run
                    var invokeMethod = m.CreateDelegate(typeof(Action<int>)) as Action<int>;

                    // All the benchmarks methods in this test use [InlineData] to specify how many times and with
                    // what arguments they should be run.
                    foreach (InlineDataAttribute dataAttr in m.GetCustomAttributes<InlineDataAttribute>())
                    {
                        foreach (object[] data in dataAttr.GetData(m))
                        {
                            // All the benchmark methods in this test take a single int parameter
                            invokeMethod((int)data[0]);
                        }
                    }
                }
            }

            // The only failure modes are crash/exception.
            return 100;
        }
    }
}