Question Shared vs. Instanced Methods - impact on a Windows app?

Administrator

VB.NET Forum Admin
Joined
Jun 3, 2004
Messages
1,462
Programming Experience
10+
I'm curious of the impact of using shared (static) methods vs. instanced. Take for example I want to save a text file to the hard drive. I would use code such as Friend Shared Function WriteToDisk(byVal textData). It's simply easier than creating an instance of the class to access the method.

But what are the consequences? I'm mainly interested in memory, not threading issues. In a main application (EXE) or a class library (DLL) that serves only this EXE, is it really required to instance? My concern is memory, will memory just grow and grow or will it matter?

For libraries shared by my web apps I definitely make them instanced and implement IDisposable where possible. But I'm wondering if I'm walking down a path of memory issues to come by using Shared methods vice instanced.

Your thoughts on this "pattern?"
 
This is more of a logical issue than a practical one. If you use an instance method then you create an object on the heap. If you use a static method you don't. There's no increasing of memory usage in either case other than the space to store the data associated with the instance in that case. Whether or not to declare a method Shared or not should not be decided on the basis of factors like memory usage. It should be decided solely on whether the method is logically a member of the class itself or a member of an object of that type.
 
The code that implements a method only exists in one place anyway. Dont be thinking that because you have a million strings in your app, there are megabytes and megabytes of memory used up by a million duplicate compiled instructions to implement the Replace() method

i.e. Suppose the bytecode that implements Replace requires 1000 bytes of memory. Now make 1000 strings containing 1 character each. Memory consumption is 1 copy of Replace @ 1000 bytes, plus 1000 single character strings (ok, unicode so 1 char is 2 bytes) total memory consumed is 3000 bytes.. it is NOT 1002000 bytes. There are not a thousand copies of Replace() lying around.


Making something shared allows it to be accessible without using an instance reference. Only use it for things that make sense to access in this way, such as creators or factory methods:

HttpWebRequest.Create(myUrl) 'a static method, factory style
 
Back
Top