Repository navigation
Expand file tree
/
Copy pathStackBenchmark.cs
More file actions
62 lines (54 loc) · 1.75 KB
/
Copy pathStackBenchmark.cs
File metadata and controls
62 lines (54 loc) · 1.75 KB
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
using BenchmarkDotNet.Attributes;
using System.Collections.Generic;
namespace PracticalDotNetCollections.Benchmarks.Iteration;
/// <summary>
/// Benchmarks evaluating standard <see cref="Stack{T}"/> performance characteristics.
/// Measures dynamic array tail expansion, up-front capacity optimizations, and list tail deletion alternatives.
/// </summary>
[MemoryDiagnoser]
public class StackBenchmark {
/// <summary>
/// The number of entries processed inside the tracking sequences.
/// </summary>
[Params(1_000, 10_000)]
public int N;
/// <summary>
/// Measures baseline sequential pushes and pops forcing dynamic internal array resizing loops.
/// </summary>
[Benchmark]
public void StackThroughput() {
var stack = new Stack<int>();
for (int i = 0; i < N; i++) {
stack.Push(i);
}
while (stack.Count > 0) {
stack.Pop();
}
}
/// <summary>
/// Demonstrates the optimization fix: specifying the expected capacity upfront to eliminate internal array expansions.
/// </summary>
[Benchmark]
public void PreSizedStackThroughput() {
var stack = new Stack<int>(N);
for (int i = 0; i < N; i++) {
stack.Push(i);
}
while (stack.Count > 0) {
stack.Pop();
}
}
/// <summary>
/// Measures baseline sequential entry mutations into a standard mutable List handling additions and removals strictly from its tail.
/// </summary>
[Benchmark]
public void ListAddRemoveFromEnd() {
var list = new List<int>();
for (int i = 0; i < N; i++) {
list.Add(i);
}
while (list.Count > 0) {
list.RemoveAt(list.Count - 1);
}
}
}