C# static vs instance methods

后端 未结 8 688
再見小時候
再見小時候 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:37

    You don't need a method "Rename" at all; you already have one, it's the setter of the Name property. Instance methods do not require more and more memory on a per instance basis, that would be silly.

    Don't make design decisions like this before profiling your code. Adding an instance method to a class is not going to cause a performance bottleneck, and even if it did, you shouldn't start out with a bad design based on a guess; prove it is a bottleneck and make adjustments as necessary.

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

    The amount of instances of a class, does not effect how much memory the method uses.

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

    It doesn't make a difference, methods (static or instance) are only loaded once into memory and JIted, they don't consume more memory just because they are instance methods.

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

    In addition to Guffa's answer:

    Methods only exist once in memory, regardless if they are static or not, so there is no difference at all in memory usage.

    The instance method has a class instance passed to it as an invisible(which can be explicitly accessed through this) parameter, essentially making the newName of void Rename(string newName) a second parameter passed to your instance method; thus the resulting burned instructions for static void RenamePet(Pet pet, string newName) and void Rename(string newName) look essentially the same, so they has no differences on performance or whatsoever

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

    Methods only exist once in memory, regardless if they are static or not, so there is no difference at all in memory usage.

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

    With respect to memory static and instance methods are same except the fact that instance methods can contain data members where as static methods can have only static data members.

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