Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is this TrySZBinarySearch implemented? [closed]

Whilst I was studying some micro performance techniques, I encountered, in the array.cs file, in the .net framework an external reference to a function for binary searches.

private static extern bool TrySZBinarySearch(Array sourceArray, int sourceIndex, int count, Object value, out int retVal); 

Where can I find documentation for this function? Or better, how it was implemented? Why is there so many SZ`s in the .net?

private static extern bool TrySZIndexOf(Array sourceArray, int sourceIndex, int count, Object value, out int retVal); 

private static extern bool TrySZLastIndexOf(Array sourceArray, int sourceIndex, int count, Object value, out int retVal);

sealed class SZArrayHelper { ... }

etc

like image 652
marcelo-ferraz Avatar asked Mar 22 '23 18:03

marcelo-ferraz


1 Answers

    [System.Security.SecurityCritical]  // auto-generated
    [ResourceExposure(ResourceScope.None)]
    [MethodImplAttribute(MethodImplOptions.InternalCall)]
    [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
    private static extern bool TrySZBinarySearch(Array sourceArray, 
        int sourceIndex, int count, Object value, out int retVal);

That's the declaration as retrieved from the Reference Source. Which has the vast majority of the source code of the .NET framework. You can download it here.

Methods that are attributed with [MethodImpl(MethodImplOptions.InternalCall)] are written in C++ and included in the CLR. Source code for the CLR is available as well from SSCLI20, a shared source version of the CLR meant to help getting .NET ported to other operating systems. It is a bit dated since it was released at the .NET 2.0 time frame but lots of primary helper functions are still accurate. You can download it here.

You'll find TrySZBinarySearch back in clr/src/vm/ecall.cpp, the first place to look for InternalCall methods. You'll see it maps to the ArrayHelper::TrySZBinarySearch() C++ method which you'll find back in clr/src/vm/comarrayhelper.cpp

Nothing terribly interesting about it, just a plain binary search algorithm that's specialized for the various simple value types. You'll find the reason it was written in C++ instead of C# in this answer.

SZ is short for single-dimension zero-based, the kind of array you'll get from a C# array[] declaration. Better known as "vector" in C# speak. Heavily micro-optimized since it is so commonly used.

UPDATE: easier to see today with the CoreCLR source code provided at github, the function is here.

like image 168
Hans Passant Avatar answered Apr 06 '23 19:04

Hans Passant