29

My whole development team thinks, static methods are a terrible thing to use.

I really don't see any disadvantages in some cases. When I needed a stateless method before, I always used static methods for that purpose.

I agree with some of their points, e.g. I know they are quite hard to test (although it's not impossible).

What I don't get is, that they claim, static methods are always held in memory and will fill the basic memory usage. So, if you are using 100 static methods in your program, when the program starts all methods are loaded into memory and will fill the memory unnecessarily. Furthermore static methods increase the risk of memory leaks.

Is that true?

It's quite inconvenient to have to create a new instance of a class just to call the method. But thats how they do it right now, the create a instance in mid of a method and call that method, that could be just a static one.

Charles Taylor
  • 686
  • 6
  • 23
Jannik
  • 2,310
  • 6
  • 32
  • 61
  • http://programmers.stackexchange.com/questions/161222/dont-use-static-in-c – Irshad Dec 08 '15 at 06:31
  • And this; http://stackoverflow.com/questions/12279438/performance-of-static-methods-vs-instance-methods – Irshad Dec 08 '15 at 06:32
  • 2
    _"My whole development team thinks, static methods are a terrible thing to use"_ - I guess they steer clear of useful things like `String.Compare()` too? –  Dec 08 '15 at 06:33
  • Seems like nonsense to me. A method is translated into some IL instructions, and these instructions are JIT compiled if a method call resolves to the appropriate method. The only significant memory cost here is that the JITted instructions then gets cached, but there's no difference among static and instance methods there. Personally I think static methods express stateless functions much more clearly, but if everyone on your team wants to follow this approach, that's what you should do too. – Asad Saeeduddin Dec 08 '15 at 06:39
  • As far as memory consumption is concerned, static methods shouldn't be any different than regular instance methods. The only memory they occupy is the instructions required to implement them. And any time a class is used, it will be loaded in memory, whether it's a static method or an instance method. – Jeff Mercado Dec 08 '15 at 06:40
  • All *methods* (i.e. *executable* code) is supposed to be in memory. – Dmitry Bychenko Dec 08 '15 at 06:43
  • 3
    Are you referring to static *methods* or static *fields*? Static methods are just plain functions, and if they don't mutate any shared state, they are in fact easy to test. Static *fields*, on the contrary, prevent the GC from collecting whatever they are pointing to, which can potentially last throughout the lifetime of your app. But under the hood, there is little difference between static and instance methods, except that instance methods get an additional `this` parameter passed implicitly. They all reside in memory as instructions. – vgru Dec 08 '15 at 06:57
  • Thanks you all for the information provided. Just to clarify this, like I've stated in my title, I am talking about static methods. – Jannik Dec 08 '15 at 07:05
  • I don't get what you're saying, "hard to test". Like @Groo said, static methods in themselves are no harder to test than non-static methods. Using your own static methods (e.g. `MyHelper.DoAwesomeStuff()`) inside other methods may arguably be of some concern when unit testing the latter, but if so, that's not on account of the "external reference" being static. – Oskar Lindberg Dec 08 '15 at 08:26
  • 1
    @Jannik: there is one distinction you need to keep in mind, and that is that using public static methods from *other* classes is indeed problematic because it makes the *caller class* harder to test (not the static method itself). The reason is that your callers end up with hard wired dependencies to these static methods and you don't have a possibility to "inject" other implementations or mock this functionality for testing. But using `new Object().DoSomething()` has exactly the same issues. Apart from "utility" methods, it is very likely that any static method you write should be `private`. – vgru Dec 08 '15 at 09:00
  • Ok, you're right, the testability seems to stay the same using both approaches. – Jannik Dec 08 '15 at 09:03
  • I spoke to one of our most experienced developers and he told me, that are doing the non-static approach, cause with instance methods they can use wrappers to wrap those methods away. Well, please don't ask me, why the heck they decided to use wrappers instead of a mocking framework, guess they were quite unexperienced back in that time, where they began the project. – Jannik Dec 08 '15 at 13:33

2 Answers2

31

There is no distinction between static and instance methods as far as memory is concerned. Instance methods only have an extra argument, this. Everything else is exactly the same. Also the basic way in which extension methods were easy to add to C#, all that was needed was syntax to expose that hidden this argument.

Methods occupy space for their machine code, the actual code that the processor executes. And a table that describes how the method stores objects, that helps the garbage collector to discover object roots held in local variables and CPU registers. This space is taken from the "loader heap", an internal data structure that the CLR creates that is associated with the AppDomain. Happens just once, when the method first executes, just-in-time. Releasing that space requires unloading that appdomain. Static variables are also allocated in the loader heap.

Do not throw away the big advantage of static methods. They can greatly improve the readability and maintainability of code. Thanks to their contract, they cannot alter the object state. They can therefore have very few side-effects, makes it really easy to reason about what they do. However, if they make you add static variables then they do the exact opposite, global variables are evil.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
18

It's quite inconvenient to have to create a new instance of a class just to call the method. But thats how they do it right now

They are being ridiculous, to be blunt.

As commenter Groo has pointed out, at the native compiled level, an instance method isn't even all that different from a static method. It's just that there's an implicit parameter being passed to the instance method, while with the static method "what you see is what you get".

The runtime may optimize access to a method. It may not JIT-compile the method until the first time it's executed. It may not even load the IL from your assembly into memory until the IL is actually needed. But it can perform these optimizations with static and instance methods equally well.

In fact, forcing all methods to be instance methods is worse than using static method, because it means that for some methods, one is arbitrarily creating an otherwise-useless object. While the runtime may be able to detect the object reference is unused and so cause it to have a minimum lifespan, it can't avoid allocating the object altogether, even a degenerate object will take up some memory while it's alive, and it will add to the cost of garbage collection.


And beyond all that, let's suppose for a moment your colleagues were correct. What would you have gained? Any measurable performance difference at all? Doubtful. Let's face it: managed code, and especially C#, has the potential to hide any number of performance-draining implementation details from us. The main reason we use a managed code language like C# is that we gain so much in productivity and code-correctness, that these possible inefficiencies are well worth it. Most of the time, and especially on modern computers, they are practically invisible.

As it happens, your colleagues are not correct, and it is not in any way beneficial to make into instance methods, methods that otherwise could be static methods. But even if that wasn't the case, to spend time writing obfuscated, unexpressive code to avoid some unmeasured, unproven performance cost is a waste. (And I know no one bothered to compare the actual performance difference, because if they had, they'd have found no improvement in performance by eliminating all static methods).

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136