Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# static vs instance methods

Tags:

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 at a given time. Now, the other option is creating a static class with a static method, and just create the [static] method there, instead of an instance method in the class. Something like so:

This:

public static class PetOwner {     public static void RenamePet(Pet pet, string newName)     {         pet.Name = newName;     } } 

Instead of this:

public class Pet {     public string Name { get; set; }      public void Rename(string newName)     {         this.Name = newName;     } } 

I'm just wondering if the static class alternative would take considerably less memory.

Thanks!

like image 798
Carlo Avatar asked Jan 22 '11 00:01

Carlo


1 Answers

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).

like image 112
Quick Joe Smith Avatar answered Sep 21 '22 12:09

Quick Joe Smith