Is there a memory or performance difference to define and use methods statically instead of using methods inside of instantiated classes? Does the method itself hog memory with each instance of the class, when the method is not static?
Perhaps any variables declared in the static method would be un-threadsafe?
/// <summary>
/// A class using instance methods (non-static)
/// </summary>
public class Junk
{
public int x {get; protected set;}
public Junk(int x = 0)
{
this.x = x;
}
public void Increment()
{
this.x++;
}
}
versus
/// <summary>
/// A class using static methods
/// </summary>
public class Junk
{
public int x {get; protected set;}
public Junk(int x = 0)
{
this.x = x;
}
public static void Increment(Junk thisJunk)
{
thisJunk.x++;
}
}
There's no difference. As your example shows, an instance method is logically nothing more than a static method where the first parameter is named "this". The only difference is that "this" is automatically checked for nullity in an instance method; it is not in a static method.
Now, virtual methods do cause a performance cost because the method that is actually invoked must be computed at runtime, not at compile time. That can add up to several nanoseconds to the runtime of your program, and it also precludes certain optimizations, such as inlining.
As for thread safety: whether a variable is used safely or not is a property of the entire program, not a property of whether a method is static or not.
No; instance methods do not take up any space per-instance. Even virtual methods don't do that - there is only one method table that is used by all instances.
That said, there is a very minor performance difference: instance methods take the this reference as a hidden parameter, and the callsite may need to check for null references. This makes calling the method slightly more expensive, but the difference almost never matters.
Although in your example, I highly suspect the JIT compiler will inline the method (whether it is static or not) and generate identical code either way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With