Part 1: Method Call Cheat Sheet

Revisit the VMT & IMT cheatsheet. As a self-practice exercise, review the following code snippets and try to answer the inline questions. To check your answers, use the ILSpy tool and run the program, but only after thinking through each situation thoroughly and consulting the cheat sheet.

Variant 1

A a = new B();
a.m1(); // Which method call will the C# compiler generate? Which method will be called at runtime?
a.m2(); // Which method call will the C# compiler generate? Which method will be called at runtime?

B b = new B();
b.m1(); // Which method call will the C# compiler generate? Which method will be called at runtime?
b.m2(); // Which method call will the C# compiler generate? Which method will be called at runtime?

class A {
    public void m1() {
        Console.WriteLine("A.m1()");
    }

    public void m2() {
        Console.WriteLine("A.m2()");
    }
}

class B : A {
    public new void m1() {
        Console.WriteLine("B.m1()");
    }

    public new void m2() {
        Console.WriteLine("B.m2()");
    }
}

Variant 2

I1 i1 = new A();
i1.m1(); // Which method call will the C# compiler generate? Which method will be called at runtime?
i1.m2(); // Which method call will the C# compiler generate? Which method will be called at runtime?

i1 = new B();
i1.m1(); // Which method call will the C# compiler generate? Which method will be called at runtime?
i1.m2(); // Which method call will the C# compiler generate? Which method will be called at runtime?

interface I1
{
    public void m1();
    public void m2();
}

class A : I1 {
    public void m1() {
        Console.WriteLine("A.m1()");
    }

    public void m2() {
        Console.WriteLine("A.m2()");
    }
}

class B : A {
    public new void m1() {
        Console.WriteLine("B.m1()");
    }

    public new void m2() {
        Console.WriteLine("B.m2()");
    }
}

Variant 3

I1 i1 = new A();
i1.m1(); // Which method call will the C# compiler generate? Which method will be called at runtime?
i1.m2(); // Which method call will the C# compiler generate? Which method will be called at runtime?

i1 = new B();
i1.m1(); // Which method call will the C# compiler generate? Which method will be called at runtime?
i1.m2(); // Which method call will the C# compiler generate? Which method will be called at runtime?

interface I1
{
    public void m1();
    public void m2();
}

class A : I1 {
    public void m1() {
        Console.WriteLine("A.m1()");
    }

    public void m2() {
        Console.WriteLine("A.m2()");
    }
}

class B : A, I1 {
    public new void m1() {
        Console.WriteLine("B.m1()");
    }

    public new void m2() {
        Console.WriteLine("B.m2()");
    }
}

Variant 4

In this case, see if you can figure out how to modify the definition (not the implementation) of class A or class B, without modifying the top-level statements, so that the program prints what is described in the comments. Answer

I1 i1 = new B();
i1.m1(); // Should print A.m1()
i1.m2(); // Should print B.m2()

interface I1
{
    public void m1();
    public void m2();
}

class A : I1 {
    public void m1() {
        Console.WriteLine("A.m1()");
    }

    public void m2() {
        Console.WriteLine("A.m2()");
    }
}

class B : A {
    public new void m1() {
        Console.WriteLine("B.m1()");
    }

    public new void m2() {
        Console.WriteLine("B.m2()");
    }
}

Part 2: Benchmarks (Scenario 2) — Incrementing a value in Dictionary

All three approaches to incrementing a value in Dictionary<string, int> have two distinct variants:

IncrementWordCount_V1 either throws an exception or doesn’t. V2 uses an explicit if, while V3 uses a very similar if hidden inside the implementation of Dictionary.TryGetValue.

Executing these two variants exercises different parts of the Dictionary code, which affects the benchmark results. Therefore, it might make sense to benchmark them separately.

Variant Found (++)

If we want to test the second variant (i.e., ++), the setup is straightforward:

Dictionary<string, int> dictionary = new();
dictionary.Add("word", 1);
for (int i = 0; i < AsManyAsIWant; ++i)
    IncrementWordCount_Vx(dictionary, "word");

This produces the following results:

| Method                 | Mean        | Error     | StdDev     | Median      |
|----------------------- |------------:|----------:|-----------:|------------:|
| TryCatch_Found    (V1) |    904.3 ns |  38.62 ns |   355.6 ns |    800.0 ns |
| ContainsKey_Found (V2) |  1,258.4 ns |  16.43 ns |   155.0 ns |  1,300.0 ns |
| TryGetValue_Found (V3) |  1,162.4 ns |  18.92 ns |   178.2 ns |  1,150.0 ns |

Wait a minute, didn’t we agree that exceptions are expensive? This clearly doesn’t seem to be the case. Think about why exceptions aren’t slow. Answer.

The difference between V2 and V3 is not very noticeable and might just be measurement error, but when we compare them with V1, there is clearly a difference. To understand why, we have to understand the code, notably dictionary[word]++.

All the details will be explained during a lecture at some point, but for now, it’s necessary to understand that the ++ operator is basically shorthand for dictionary[word] = dictionary[word] + 1.

With this knowledge, how many times do the variants V1, V2, V3 access the dictionary? Answer.

Variant NotFound (= 1)

The problem is that the previous approach doesn’t work. The first call to IncrementWordCount modifies the data structure, so subsequent calls to IncrementWordCount would benchmark the previous variant.

First, we should think about what we actually want to test in this case. As before, we likely want to run the method multiple times to get more precise results:

Generally, there is a difference between these two. If adding a new element to the data structure depends on the number of elements in the data structure, there is a difference between 10 x 1_000_000 and 1_000_000 x 10, even though the total is the same.

Luckily for us, the complexity of .Add for Dictionary is O(1), so theoretically, there should not be a difference between adding the first element and adding the millionth element. Practically, there might be some difference.

Can you spot what is wrong with the following approach? Answer

for (int i = 0; i < AsManyAsIWant; ++i) {
    Dictionary<string, int> dictionary = new();
    IncrementWordCount_Vx(dictionary, "word");
}

A better approach would be:

Dictionary<string, int> dictionary = new();
for (int i = 0; i < AsManyAsIWant; ++i) {
    IncrementWordCount_Vx(dictionary, GetUniqueWord());
}

How would we implement GetUniqueWord though? Idea

All of this sounds like a problem that arises in every benchmark. Therefore, it might make sense to see whether the BenchmarkDotNet framework can help us in this case. There are two attributes that might be useful:

We can put the allocation of new Dictionary into [IterationSetup] and then measure just the addition of the word, letting the framework handle the execution of the method multiple times. However, we have to ask for this explicitly: [IterationSetup] disables the benchmark iterations, so we have to configure the iteration count manually. (By the way, the BenchmarkDotNet documentation explicitly advises against using [IterationSetup] for microbenchmarks. There are other, possibly better, approaches. Some ideas were discussed during the live labs)

| TryCatch_NotFound    | 38,754.6 ns | 363.78 ns | 3,382.5 ns | 38,700.0 ns |
| ContainsKey_NotFound |  2,570.4 ns |  34.80 ns |   328.6 ns |  2,500.0 ns |
| TryGetValue_NotFound |  2,570.5 ns |  29.85 ns |   281.6 ns |  2,500.0 ns |

The individual results are one thing, but when considering an approach in the context of the homework assignment, it’s important to note that the Found and NotFound variants are mixed together for real data.

Part 3: Benchmarks (Scenario 1) — Data structure choice

This is likely no longer a microbenchmark. The complexity of operations on the data structures usually depends on the number of elements in the data structure (unless it’s O(1)). We likely need to measure the behaviour of the data structures using some realistic input data.

Before we do that, it might make sense to think about this and try to predict the results. The complexity of the data structures can usually be found in the documentation. In some cases, inspecting the source code of .NET might also be helpful. Although the code is publicly available on GitHub, it is spread across various repositories. The source.dot.net tool is helpful here. This helps us realize the following:

Data structure Addition Lookup Sort
SortedList O(N) O(log(N)) O(1)
SortedDictionary O(log(N)) O(log(N)) O(1)
Dictionary O(1) O(1) O(N * log(N))

The whole assignment then performs some additions and lookups for every word, followed by sorting and printing:

Data structure Total
SortedList N * N + 1 + N (or N * log(N) + 1 + N)
SortedDictionary N * log(N) + 1 + N
Dictionary N * 1 + N * log(N) + N

The theoretical complexities are very similar, but if you tried this yourself with large input files, you found that Dictionary is better. Why is that? Answer

Part 4: Feedback on unit testing the TableSummatorProcessor assignment

The TableSummator, as an ITokenProcessor, can’t be easily unit tested because its API is private (ProcessHeader and ProcessBody). We need to realize that the class actually serves three purposes:

c) could be an inherent part of TableSummator, but a) and b) can be handled by individual classes, as the input and output are very well defined. Therefore, it would be better to split the implementation as follows:

class HeaderProcessor {
    public int ColumnId { get; }
    public int ColumnAmount { get; }

    public void ProcessToken(Token token) { ... }
}

class BodyProcessor {
    public int ColumnSum { get; }

    public BodyProcessor(??? input) { ... }
    public void ProcessToken(Token token) { ... }
}

class TableSummator : ITokenProcessor {
    private HeaderProcessor headerProcessor;
    private BodyProcessor bodyProcessor;

    public void ProcessToken(Token token) {
        if (...)
            headerProcessor.ProcessToken(token);
        else
            bodyProcessor.ProcessToken(token);
    }

    public void ReportResult() { ... }
}

There is one more question: how should we pass the input to BodyProcessor? Passing the whole HeaderProcessor provides more information than necessary. BodyProcessor doesn’t need the whole object; just the properties are enough. Therefore, in the BodyProcessor constructor, we accept (int columnId, int columnAmount). If we needed to pass more data, we could generalize this to a record struct BodyProcessorConfig(...) and pass that instead.