Last active
October 21, 2022 23:21
-
-
Save mandarinx/cc7ac3c39eccf0d21045556b9f0c0b43 to your computer and use it in GitHub Desktop.
C# function call performance cost
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using UnityEngine; | |
public interface InterfaceFunc { | |
void InterfaceFn(); | |
} | |
static public class MonoExtension { | |
static public void ExtFunc(this MonoBehaviour mb) {} | |
} | |
public class FnPerfTest : MonoBehaviour, InterfaceFunc { | |
private const int reps = 10000000; | |
private string report; | |
void Start() { | |
Stopwatch stopwatch = new Stopwatch(); | |
StartTest(stopwatch); | |
for (var i = 0; i < reps; ++i) { | |
StaticFunction(); | |
} | |
long staticFunctionTime = StopTest(stopwatch); | |
StartTest(stopwatch); | |
for (var i = 0; i < reps; ++i) { | |
this.ExtFunc(); | |
} | |
long extensionMethodTime = StopTest(stopwatch); | |
StartTest(stopwatch); | |
for (var i = 0; i < reps; ++i) { | |
InstanceFunction(); | |
} | |
long instanceFunctionTime = StopTest(stopwatch); | |
StartTest(stopwatch); | |
for (var i = 0; i < reps; ++i) { | |
InterfaceFn(); | |
} | |
long interfaceFunctionTime = StopTest(stopwatch); | |
StartTest(stopwatch); | |
for (var i = 0; i < reps; ++i) { | |
VirtualFunction(); | |
} | |
long virtualFunctionTime = StopTest(stopwatch); | |
StartTest(stopwatch); | |
Action lambda = () => {}; | |
for (var i = 0; i < reps; ++i) { | |
lambda(); | |
} | |
long lambdaTime = StopTest(stopwatch); | |
StartTest(stopwatch); | |
Action del = delegate{}; | |
for (var i = 0; i < reps; ++i) { | |
del(); | |
} | |
long delegateTime = StopTest(stopwatch); | |
StartTest(stopwatch); | |
// for (var i = 0; i < reps; ++i) { | |
// SendMessage("InstanceFunction"); | |
// } | |
long sendMessageTime = StopTest(stopwatch); | |
report = "Test,Time\n" + | |
"Static Function," + staticFunctionTime + "\n" + | |
"Extension Method," + extensionMethodTime + "\n" + | |
"Instance Function," + instanceFunctionTime + "\n" + | |
"Interface Function," + interfaceFunctionTime + "\n" + | |
"Virtual Function," + virtualFunctionTime + "\n" + | |
"Lambda," + lambdaTime + "\n" + | |
"Delegate," + delegateTime + "\n" + | |
"SendMessage," + sendMessageTime; | |
} | |
private void StartTest(Stopwatch sw) { | |
sw.Reset(); | |
sw.Start(); | |
} | |
private long StopTest(Stopwatch sw) { | |
return sw.ElapsedMilliseconds; | |
} | |
void OnGUI() { | |
GUI.TextArea(new Rect(0, 0, Screen.width, Screen.height), report); | |
} | |
public static void StaticFunction() {} | |
public void InstanceFunction() {} | |
public virtual void VirtualFunction() {} | |
public void InterfaceFn() {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment