Will a single-line method hit performance?

ValidateRequestmethod defined in code

    private bool ValidateRequest()
    {
        return _doc != null;
    }

This method is called externally, I want to check if _doc is null. This method was used 5 times in the cs file.

Performance point of view, it is advisable to define a method with only one line? I think that before calling this method, everything from the called will be pushed onto the stack even after it is pulled from the stack.

Any thoughts?

=== Edit ====

I am using .NET version 3.5

+3
source share
4 answers

ok, so this is only from LinqPad, and I don’t think the final answer, but the following code generated a slight mismatch: (00: 00: 00.7360736 vs 00: 00: 00.0740074)

void Main()
{
    var starttime = DateTime.Now;
    for (var i = 0; i < 1000000000; i++)
    {
        if (ValidateRequest()) continue;
    }
    var endtime = DateTime.Now;
    Console.WriteLine(endtime.Subtract(starttime));

    starttime = DateTime.Now;
    for (var i = 0; i < 100000000; i++)
    {
        if (_doc != null) continue;
    }
    endtime = DateTime.Now;
    Console.WriteLine(endtime.Subtract(starttime));
}

private object _doc = null;

private bool ValidateRequest()
    {
        return _doc != null;
    }
+1
source

, . , , JIT . , , .

, . .

+7

. , , , IL .

If this method helps with maintainability of the code, as it links intention, continue with it.

+6
source

As always: when in doubt, a benchmark!
And when you test, do it in release mode , otherwise you do not compare with compiler optimization.

After that, if it really affects performance, you can embed it in NGen.
This SO post says it.

+5
source

All Articles