C# static vs instance methods

后端 未结 8 689
再見小時候
再見小時候 2020-12-05 18:10

I\'m risking it this might be a newb question but here goes. I\'m tempted to add a method to a class that could possible have thousands and thousands of instances in memory

相关标签:
8条回答
  • 2020-12-05 18:57

    In case of memory it doesn't make any difference,Methods exist only once in the memory regardless of being static or instance but static methods are minutely faster to invoke than instance methods because Instance meth­ods actu­ally use the ‘this’ instance pointer as the first para­me­ter, so an instance method will always have that over­head

    So static methods have little advantage over instance methods in case of performance but for memory usage they both use same amount.

    0 讨论(0)
  • 2020-12-05 18:59

    Only data fields require storage per instance, subject to certain conditions and optimisations. For instance, 10,000 instances of a class that define an Int32 member will consume ~40,000 bytes of memory.

    Strings, on the other hand, are not so simple due to interning. You can try this as an example:

    object.ReferenceEquals("", string.Empty) // returns true!
    

    If the same 10,000 instances also define a string, and that string is the same for each instance, then you're going to have 10,000 references pointing at the same data, reducing overhead considerably (but in a 32-bit environment, there's another 40,000 bytes taken up by the references).

    Methods, as pointed out by others, whether static or instance, are only loaded once.

    The decision to use either instance or static methods is not influenced by performance reasons, but by how the method is intended to be used. In your case, the method requires an instance of the type as its first parameter so it may as well be an instance method.

    Static methods, in my experience, are most useful as an alternative to a type's constructor for returning a new instance. Constructors, once invoked, have to either return a new instance or throw an exception, which may not be desirable. Static methods can return null if something fails, or return a cached instance (the latter of which is useful if the constructor is an expensive operation).

    0 讨论(0)
提交回复
热议问题