Static variable vs Static method in C# - c#

As per my knowledge, it is not advisable to use static variables in Web Applications. Now my question is, is it advisable to use static methods in web applications?is a static method use system memory as a static variable use?
please clarify my doubt.
Thanx in advance.

Yes, it is advisable to use static methods in a web application.
A static variable has very limited use in a web application, because all threads will share the same variable.
When it comes to methods, it's not a problem that all the threads access the same method, as the method itself won't change. The local data in a method is still separate for each call to the method, so several threads calling the same method at the same time is not a problem.
Generally speaking, if a method doesn't rely on any instance data, it should be static. I.e. if a method can be static (without any other chances to the method), it should be.

The reason you should avoid static variables is that they are often used to provide global state. This breaks encapsulation and makes maintaining and debugging programmes harder as any piece of code could change your variable.
In a threaded environment like ASP.NET this made worse by multiple threads potentially editing the same static variable's contents with non-deterministic results.
Static methods on the other hand can be a very good thing. They provide referential transparency which means the same inputs will always produce the same output and there's no side-effects changing state. This makes multi-threaded access much easier to reason about as threads cannot affect the processing of others by changing shared variables (assuming you're not using static variables of course).
It can also make unit testing easier and more robust as you don't need to test the underlying state of the world alongside your inputs and expected outputs.

It's advised to avoid static data because it introduces concurrency issues if the data is mutable.
Static methods that do not utilize mutable static data need not be avoided; sometimes they make sense for functionality that doesn't need to be specific to any specific instance.

Related

Are static methods always held in memory?

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

c# Static or Non Static Class

I have a c# windows forms mp3 player application. I have the audio files in my Resources folder and a separate "MyAudio" static class which handles all the audio related work like playing and increasing volume etc.
From my Form, I just call the play method using:
MyAudio.Play(track);
In the MyAudio class, I have a WindowsMediaPlayer object declared as:
private static WindowsMediaPlayer obj=new WindowsMediaPlayer();
My Question is, in terms of efficiency and less memory usage, is it better to declare MyAudio class as static or non static? Is it wise to create a Object of the MyAudio class in form and then call the methods or directly call using class Name?
Also is it good practice to declare the instance variables as static?
Your question is indeed broad, but there are few design principles that you can take care of, while you are designing a class:
Do I need the object and it's state throughout the application lifetime
Do I need to maintain the state of class variables for future use
Do I need to multi-thread or parallelize the application at any point of time
Do I need to decouple the component in the future and used in other scenarios like Ajax based web scenario
Important thing in this case is that you are keen to maintain the state for the application lifetime and the amount of memory usage is fine for the application environment, since after initializing you would be able to get all the data from memory and don't need to query a source like database. However, this is good for the scenario where you need to initialize once and read as a static information in the rest of the application. In case you plan to re query the information, then the part purpose of using static type would be lost
Let's assume in the future you need to parallelize your code for performance enhancement, then static will come to haunt you, since it would be shared among threads and invariably would need a synchronization construct like lock, mutex, which will serialize all threads and thus purpose would be lost. Same things would happen in a Web / Ajax scenario and your static component cannot handle the multiple parallel requests and will get corrupted until and unless synchronized. Here instance variable per thread is a boon, as they do task / data parallelization without requiring a lock, mutex
In my understanding static is a convenience, which many programmers misuse, by avoiding the instance variable and using at will, without understanding the implications. From the GC perspective, it cannot collect the static variable, so the working set of the application would invariably increase till it stabilize and will not decrease until and unless explicitly released by program, which is not good for any application, until and unless we are storing data to avoid network database calls.
Ideal design would suggest to always use the instance class, which gets created, does its work and gets released, not linger around. In case there's information that needs to be passed from one function to another like in your case from Play to Pause to Stop, then that data can be persisted to a static variable and modified in a thread safe manner, which is a much better approach
If we just take example given by you since it's a windows form, which does operations like Play, then static would be fine, as it is an executable running on a system, but for testing imagine a scenario that you initiate multiple instances by double clicking and play around on each one, by pressing different operations, then they all will access same static object and you may get a corruption issue, in fact to resolve such scenario you may even chose your class to be singleton, where at a given moment no more than one instance can exist in the memory, like it happens for Yahoo messenger, no matter how many times you click, always same instance comes up.
There are no static instance variables. However its best practice to define static members if they don't have anything to do with a particular instance of the class.

Should I use static function in c# where many calls the same func?

John's console application calls my DLL function many times (~15x per sec). I am thinking to put this function as a static method.
I know that :
It can only access static props and objects.
It doesn't need an instance to run the function.
But I don't know if these are the only questions which i need to ask myself.
Each John's calls to my function is in a new thread that he creates.
If there is an error in my function, how will this affect all other calls?
Should I make this function a regular function with instance to the class (which John will create)?
What about GC?
What is the best practice answer for this question?
Sounds like there could be a problem. Calling a method which operates on static (shared) objects in a multithread environment should ring some alert bells for you.
Review your code and if there's a chance that a shared object is accessed from two (or more) threads at the same time, make the object an instance field and make your methods instance methods.
Of course, whether or not there is a risk depends much on the actual code (which you don't show) but making all calls nonstatic means that you lower the potential risk.
Generally, if your static method doesn't use any state (i.e. both reading and writing to static fields and properties, or calling other static methods that do so), there won't be any side effects for the caller, no matter how many threads they start.
If you're asking for best practice, static methods are mostly a bad idea though. If at all, static methods should be only used for very generic utility functionality.
It's not recommended because you can't predict if requirements change and you need some state one day. Then you'd better use a class that the caller can instantiate, and you'll break all existing code that uses your function.
About garbage collection, yes sure that has some overhead, but that is currently the sacrifice if you go the route of memory-managed OO. If you want more control, use unsafe code or a language like C++ or Vala.
I would agree with Wiktor (+1), but would also add that if synchronization is required in the static method, it may be more efficient to use multiple instances. Otherwise, having many threads might be pointless as only one can access a critical section at a time.

Is this a good use for a static class?

I have a read only list that is shared across all instances of the application and won't change very often. Is it good practice to make a property on a static class to access this list? the list is filled from the database in the static constructor. Setting the app pool to recycle every night would guarantee the list would be up to date every day correct? Are there any reasons this is a bad idea? Thanks!
Nothing wrong with a static class. You could also use the cache, which would work in a similar way. The cache gives you the added bonus of being able to invalidate the cache on a timed basis of your choosing.
This looks like a good solution. You may want to use a sealed class instead, to avoid sub-classes messing with it.
The issue with global state is when it is being changed by the application. In this case, that's not a problem.
You should understand how static properties are stored.
Roughly, all static state is placed in the instance of RuntimeType (which, in turn, is created when static ctor is called). CLR via C# describes this mechanism in details.
In the light of that, this collection will be shared across all instances, but you should keep in mind all potential memory leaks (just imagine the situation when you're subscribing on the collection events and all pages became reachable even when they're closed etc.)
The second disadvantage of this approach is that this collection is not up-to-date.
The third disadvantage is that you need to take care about thread safety of this collection, which, in turn, will harm your performance.

Performance of very big classes

I have a class called "simulation" and a method for solving simulation.
class sim
{
void Step()
{
}
other methods (20+)...
}
Sim class is only instantiated once during the program.
Step method is called in the order of millions during the program.
Step method uses a lot of local variables (100+). None of those locals are used in other methods.
Is it better to make those local variables a member of the class or keep them as local in Step() for better performance?
It depends. What kinds of variables: primitive types or objects? If the latter, your IL code is still going to chase their pointers. If the former, it depends on what order you access them in, and what CPU you are targeting. Optimizing the layout of variables should come pretty far down the list of performance tuning activities, especially in C# when you're dependent on what assembly your IL is translated into.
As usual with optimizations: first measure performance to identify bottlenecks. Then consider what you can do to remove them. Until you know that you need to do something like that, just write your code as clearly as possible: don't expose local variables unnecessarily by lifting them into the class level. And do consider splitting that Step() method: a large method is hard to understand and therefore even harder to optimize.
As a general rule, you should minimise the scope of variables and only increase the scope if it proves absolutely necessary. Converting locals to member variables is a poor design choice, and thus needs a very strong justification.
Also note that local variables only have a cost if they have non-trivial constructors. A local variable with a noop constructor or no constructor at all has no setup cost, so it would be pointless to expand its scope.
If some of the variables contain objects that can be reused in between multiple method calls, you'd skip the overhead of disposing the old instance and creating a new instance with each method call. For example, lookups in a dependency injection container that won't change in between method calls could be 'cached' in a field.
But aside from that, you probably won't get much of a performance increase. You could give it a try and use a profiler to measure your code performance. A profiler may also help you to identify other bottlenecks in your code.

Categories