简体   繁体   中英

Will C# inline these functions?

I'm writing a performance-critical application in C# and the core operation is weight calculations. The function looks like this:

public void ForEachWeight(Action<int, int, float> action)
{
    for (int lower = 0; lower < LowerLayerSize; lower++) {
        for (int upper = 0; upper < UpperLayerSize; upper++) {
            action(lower, upper, Weights[(lower * UpperLayerSize) + upper]);
        }
    }
}

And it gets called in dozens of places with various simple functions like:

if (activationMethod == ActivationMethod.Binary) {
    ForEachWeight((lower, upper, weight) => upperLayer.Values[upper] += weight;
} else {
    ForEachWeight((lower, upper, weight) => upperLayer.Values[upper] += lowerLayer.Values[lower] * weight);
}

All the calls are done from within the same class so all the variables are accessible. Can C# inline these function calls? I'm thinking for example the above calls can be inlined to something like this:

if (activationMethod == ActivationMethod.Binary) {
    for (int lower = 0; lower < LowerLayerSize; lower++) {
        for (int upper = 0; upper < UpperLayerSize; upper++) {
            upperLayer.Values[upper] += weight;
        }
    }
} else {
    for (int lower = 0; lower < LowerLayerSize; lower++) {
        for (int upper = 0; upper < UpperLayerSize; upper++) {
            upperLayer.Values[upper] += lowerLayer.Values[lower] * weight);
        }
    }
}

If it doesn't it means tens of thousands of extra function calls which I think are a huge overhead. If this gives even a 10% speed boost it's totally worth it. I can't easily benchmark by manually inlining them for comparison since I'd have to rewrite a lot of code.

So my question is CAN C# inline these calls? And if so, how can I find out IF they have been inlined?

Inlining happens at JIT compilation, so you need to inspect code at runtime to observe inlining. This can be done using the debugger, but keep in mind that if the CLR detects the presence of a debugger various optimizations are disabled, so you need to attach the debugger after the method has been compiled.

Please see these answers for some info on how you can find the method using WinDbg/SOS.

您可以在此属性中使用MethodImplOptions.AggressiveInlining: http//msdn.microsoft.com/en-us/library/system.runtime.compilerservices.methodimplattribute.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM