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
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 {
returnthis.array[index];
}
}
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:
Unfortunately, thread-local storage comes at a cost. Reading or writing a thread-local variable is far more expensive than reading or writing a local variable. System.Collections.Immutable uses a trick or two to help ameliorate this expense. For example, System.Collections.Immutable caches thread-local variables in local variables in a method to avoid unnecessary TLS hits on repeated access. Here’s some sample code which implements this:
Thread safety. A pure function with value parameters is completely thread safe. With reference or pointer parameters, even if they are const, you do need to be aware of the danger that another thread doing non-pure operations might mutate or free the data, but it is still one of the most powerful tools for writing safe multithreaded code.