简体   繁体   中英

Is calling a method from the same class faster than calling a method from another class in C#?

Is it faster to call a method that is written in a class then to call a method from another class? For example, would something like this:

public class MainClass
{
   private void Caller()
   {
      Method1();
   }

   public void Method1()
   {
      // do something
   }
}

Would that be faster than something like:

public class MainClass
{
   private void Caller()
   {
      HolderClass.Method1();
   }
}

public class HolderClass
{
   public void Method1()
   {
      // do something
   }
}

Or are they the same? I might have to call "Method1" millions of time so a small difference could matter.

First: the general answer to such questions is measure it . Second: it should not make a difference. In the first case you call

this.Method();

in the second case

holder.Method();

So both have to resolve the reference access first. In theory, if you make Method() static it should be slightly faster because you then spare that. But this nano-scaled stuff will all be lost in other compiler decisions depending on what code Method holds. Which makes us come to third: If you intend to call that method a million times, if you can remove the method call at all, as function calls have a function call overhead . To call functions the compiler has to do a lot of bookkeeping, like holding function contexts, pushing/popping that to a stack frame and so on. Rewrite that function to be called only once and iterate a million times over your elements in that function. Instead of:

for <millions> {
    // rule one by one with a million calls
    method();
}

do:

method() {
    for <millions> {
        // rule them all in one call
    }
}

This will give you a real performance boost.

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