Compared to
This link comes up a lot in Google. For future reference, I ran a short program in C# on the cost of a function call, and the answer is: "about six times the cost of inline". Below are details, see //Output at the bottom. UPDATE: To better compare apples with apples, I changed Class1.Method to return 'void', as so: public void Method1 () { // return 0; }
Still, inline is faster by 2x: inline (avg): 610 ms; function call (avg): 1380 ms. So the answer, updated, is "about two times".
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics;
namespace FunctionCallCost { class Program { static void Main(string[] args) { Debug.WriteLine("stop1"); int iMax = 100000000; //100M DateTime funcCall1 = DateTime.Now; Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < iMax; i++)
{
//gives about 5.94 seconds to do a billion loops,
// or 0.594 for 100M, about 6 times faster than
//the method call.
}
sw.Stop();
long iE = sw.ElapsedMilliseconds;
Debug.WriteLine("elapsed time of main function (ms) is: " + iE.ToString());
Debug.WriteLine("stop2");
Class1 myClass1 = new Class1();
Stopwatch sw2 = Stopwatch.StartNew();
int dummyI;
for (int ie = 0; ie < iMax; ie++)
{
dummyI = myClass1.Method1();
}
sw2.Stop();
long iE2 = sw2.ElapsedMilliseconds;
Debug.WriteLine("elapsed time of helper class function (ms) is: " + iE2.ToString());
Debug.WriteLine("Hi3");
}
}
// Class 1 here using System; using System.Collections.Generic; using System.Linq; using System.Text;
namespace FunctionCallCost { class Class1 {
public Class1()
{
}
public int Method1 ()
{
return 0;
}
}
}
// Output: stop1 elapsed time of main function (ms) is: 595 stop2 elapsed time of helper class function (ms) is: 3780
stop1 elapsed time of main function (ms) is: 592 stop2 elapsed time of helper class function (ms) is: 4042
stop1 elapsed time of main function (ms) is: 626 stop2 elapsed time of helper class function (ms) is: 3755