1

I checked the performance of a simple method which just get the last element of an array. I found it is almost 4 times slower than the direct indexer. Any way to inline the method to get better performance?

int last(this int[] a) 
{
   return a[a.length-1];
}
Tian Xiao
  • 239
  • 2
  • 7
  • 1
    C# *compiler* doesn't inline methods but .NET Runtime (JIT) can inline methods. You may suggest JIT to inline method by using attribute as in this answer: http://stackoverflow.com/a/8746128/1779504. But you cannot force JIT to inline method. – csharpfolk May 26 '16 at 15:20
  • 1
    PS. Did you check performance using Release build, there is huge difference between Debug and Release modes – csharpfolk May 26 '16 at 15:21
  • 1
    In a quick test, the JIT compiler did in fact inline this method (well not exactly this one, I had to fix it to compile) – harold May 26 '16 at 15:21
  • 1
    This method is small enough that it should be auto-inlined by the runtime. Can you show a bit more of the code and details on how you checked performance, in case there is something unusual in your code that prevents it from auto-inlining? – Matt Jordan May 26 '16 at 15:22
  • Is this slower because you created it as an extension method? That was my assumption. – stephen.vakil May 26 '16 at 15:22
  • 1
    Why closing this question? .Net 4.5 allows inline functions. Have a look here: http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.methodimploptions%28v=VS.110%29.aspx – Failed Scientist May 26 '16 at 15:22
  • @TalhaIrfan That is *exactly* what the top answer to the linked duplicate says. – Cody Gray - on strike May 26 '16 at 15:26
  • @CodyGray Ah right!! Gotcha – Failed Scientist May 26 '16 at 15:27

0 Answers0