Csharp

Exploring the .NET CoreFX Part 12: Aggressive Inlining
Exploring the .NET CoreFX .net core csharp system.collections.immutable
Published: 2015-01-05
Exploring the .NET CoreFX Part 12: Aggressive Inlining

This is part 12/17 of my Exploring the .NET CoreFX series.

In C++, the inline keyword allows a developer to provide a hint to the compiler that a particular method should be inlined. C# has the identical ability but uses an attribute instead:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
internal class SecurePooledObject<T>
{
    ....

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    internal bool IsOwned<TCaller>(ref TCaller caller)
        where TCaller : struct, ISecurePooledObjectUser
    {
        return caller.PoolUserId == _owner;
    }
}

In System.Collections.Immutable, this attribute is used highly selectively – only once, in fact.

Read more...
Exploring the .NET CoreFX Part 11: Code Contracts
Exploring the .NET CoreFX .net core csharp system.collections.immutable
Published: 2014-12-17
Exploring the .NET CoreFX Part 11: Code Contracts

This is part 11/17 of my Exploring the .NET CoreFX series.

In 2008, Microsoft Research published Code Contracts, which provide a language-agnostic way to express coding assumptions in .NET programs. The assumptions take the form of pre-conditions, post-conditions, and object invariants.

Here is a simple example of code which uses Code Contracts:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
using System.Diagnostics.Contracts;

public class StringUtils
{
    internal static string Append(string s1, string s2)
    {
        Contract.Requires(s1 != null);
        Contract.Requires(s2 != null);
        Contract.Ensures(Contract.Result<string>() != null);
        return s1 + s2;
    }
}

Code Contracts assertions are not limited to runtime enforcement. They may instead be enforced by compile-time static analysis. For example, it is very simple to annotate methods with Code Contracts, set up a continuous integration (CI) server to perform static analysis, and fail the build if there are any failed assertions. This gives us the best of both worlds: a guarantee our code enforces our assumptions with essentially zero runtime penalty.

Read more...
Exploring the .NET CoreFX Part 10: Performance Tuning Enumeration
Exploring the .NET CoreFX .net core csharp system.collections.immutable
Published: 2014-12-02
Exploring the .NET CoreFX Part 10: Performance Tuning Enumeration

This is part 10/17 of my Exploring the .NET CoreFX series.

The .NET Core’s System.Collections.Immutable.ImmutableArray provides two enumerators. The first has been highly tuned for speed, and the second is a fallback for compatibility when it is required.

The high-performance enumerator uses the following performance optimizations:

  1. The enumerator is a struct, rather than a class, so that it is stack-allocated rather than heap-allocated.
  2. The enumerator does not implement IEnumerator or IEnumerator, as this would require it to implement IDisposable. By not implementing IDisposable the iterator will inline during foreach loops..
  3. The enumerator does not use range checks in Enumerator.Current; it requires on .NET’s array range checks to throw an exception instead.

The high-performance enumerator is called ImmutableArray.Enumerator, which is returned by ImmutableArray.GetEnumerator():

Read more...
Exploring the .NET CoreFX Part 9: Immutable Collections and the Builder Pattern
Exploring the .NET CoreFX .net core csharp system.collections.immutable
Published: 2014-12-01
Exploring the .NET CoreFX Part 9: Immutable Collections and the Builder Pattern

This is part 9/17 of my Exploring the .NET CoreFX series.

Using the builder pattern to allow for easier construction of immutable objects is well-known.

The .NET Core’s immutable collections assembly, System.Collections.Immutable, also uses the builder pattern, but for a slightly different reason: to improve the performance of making many changes to the collection. This is possible because, unlike the immutable collection itself, the builder pattern does not need to maintain the immutable collection’s invariants after each modification. The builder pattern merely needs to reestablish the invariants of the immutable collection upon the publishing of the results.

Read more...
Exploring the .NET CoreFX Part 8: NullReferenceException Performance Tricks
Exploring the .NET CoreFX .net core csharp system.collections.immutable
Published: 2014-11-28
Exploring the .NET CoreFX Part 8: NullReferenceException Performance Tricks

This is part 8/17 of my Exploring the .NET CoreFX series.

The .NET Core’s System.Collections.Immutable.ImmutableArray class implements an immutable wrapper around a normal C# managed array. This looks something like:

1
2
3
4
5
public struct ImmutableArray<T>
{
    internal T[] array;
    ...
}

ImmutableArray.array is lazy-initialized.

Within the ImmutableArray class, there are a number of methods which have the precondition that ImmutableArray.array must be initialized. These preconditions must be checked before the method begins processing to make sure we handle invalid states correctly.

Read more...
Exploring the .NET CoreFX Part 7: Reference Versus Structural Equality
Exploring the .NET CoreFX .net core csharp system.collections.immutable
Published: 2014-11-27
Exploring the .NET CoreFX Part 7: Reference Versus Structural Equality

This is part 7/17 of my Exploring the .NET CoreFX series.

In the previous post, I referenced EqualityComparer.Default. If T does not implement IEquatable, EqualityComparer.Default will use the framework-defined Object.Equals(), which implements reference equality.

However, many times you want to compare two types for structural equality (i.e. identical content) rather than reference equality (i.e. two references point to the same instance of the class). The interface IStructuralEquatable was defined to allow a class to explicitly implement structural, rather than reference equality. Related classes include IStructuralComparable and StructuralComparisons.

Read more...
Exploring the .NET CoreFX Part 6: Use IEquatable for Higher-Performance Equals()
Exploring the .NET CoreFX .net core csharp system.collections.immutable
Published: 2014-11-24
Exploring the .NET CoreFX Part 6: Use IEquatable for Higher-Performance Equals()

This is part 6/17 of my Exploring the .NET CoreFX series.

Let’s say you are writing a custom IList which contains the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public class MyList<T> : IList<T>
{
    private T[] array;

    ...

    public int IndexOf(T item)
    {
        for (int i = 0; i != array.Length; ++i) {
            if (this.array[i].Equals(item)) {
                return i;
            }
        }

        return -1;
    }
}

The above code uses T“s implementation of Object.Equals(), which is defined as:

Read more...
Exploring the .NET CoreFX Part 5: Keep Indexers Trivial to Allow JIT Optimization
Exploring the .NET CoreFX .net core csharp system.collections.immutable
Published: 2014-11-21
Exploring the .NET CoreFX Part 5: Keep Indexers Trivial to Allow JIT Optimization

This is part 5/17 of my Exploring the .NET CoreFX series.

This is a simple recommendation based on observations from System.Collections.Immutable.

Recommendations

  1. Keep the implementation of an indexer as trivial as possible to allow the JIT optimization of removing array bounds checking to work. For example, don’t check if a member variable is null; just use it and allow the NullReferenceException to happen naturally. In other words, use:
1
2
3
4
5
6
7
public T this[int index]
{
    get
    {
        return this.array[index];
    }
}

not:

Read more...
Exploring the .NET CoreFX Part 4: The Requires Convenience Class
Exploring the .NET CoreFX .net core csharp system.collections.immutable
Published: 2014-11-20
Exploring the .NET CoreFX Part 4: The Requires Convenience Class

This is part 4/17 of my Exploring the .NET CoreFX series.

The System.Collections.Immutable project in the .NET CoreFX includes a convenience class called Requires, which looks like:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
internal static class Requires
{
    [DebuggerStepThrough]
    public static T NotNull([ValidatedNotNull]T value, string parameterName)
        where T : class // ensures value-types aren't passed to a null checking method
    {
        if (value == null)
        {
            throw new ArgumentNullException(parameterName);
        }

        return value;
    }

    ...
}

This allows other methods to write code like:

Read more...
Exploring the .NET CoreFX Part 3: Making Methods Debugger-Friendly
Exploring the .NET CoreFX .net core csharp system.collections.immutable
Published: 2014-11-19
Exploring the .NET CoreFX Part 3: Making Methods Debugger-Friendly

This is part 3/17 of my Exploring the .NET CoreFX series.

System.Collections.Immutable uses a number of attributes to make it more debugger-friendly. Here are the key attributes:

DebuggerStepThrough

Occasionally a method is so simple that it doesn’t make sense to have the debugger step into it. The System.Diagnostics.DebuggerStepThroughAttribute instructs the debugger to step through the code instead of stepping into the code.

Here is an example from System.Collections.Immutable:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
internal static class Requires
{
    [DebuggerStepThrough]
    public static void Range(bool condition, string parameterName, string message = null)
    {
        if (!condition)
        {
            FailRange(parameterName, message);
        }
    }
}

DebuggerBrowsable

The System.Diagnostics.DebuggerBrowsableAttribute determines if and how a member is displayed in the debugger variable windows.

Read more...