What I would like to know is what are the most efficient ways to consume less memory in runtime .
Using "static" variables?
Create object with instances or a static class
?
Using Dispose()
to free memory, etc.
What I would like to know is what are the most efficient ways to consume less memory in runtime .
Using "static" variables?
Create object with instances or a static class
?
Using Dispose()
to free memory, etc.
The question begins a little broad. There are many ways and the subject interests me, I think it's cool to use memory-saving techniques because they help a lot in performance. Less memory used (in the heap ) brings less garbage generated, fewer queues, fewer pauses , less overhead for memory management.
Using static variables tend to spend more memory, or at least retain it for longer. If the semantics you need is this, okay use, otherwise do not use.
But its use can be very useful, not to save money, but to avoid unnecessary collections. If you know that there will be no competing access (in some cases it is possible, you just need more care) and that the object changes a few times, but it always keeps an instance of it, it may be more interesting to create an object and reuse it, it can be a "poor" way of doing an pool of objects. But you have to understand what you are doing. Done correctly creates fewer objects and generates fewer queues giving less pauses. One of the difficulties is when the object has no set size, such as strings , another is that it can lose locale and the object gets away from its container , what it can do everything slows down, there begins to create the problem that languages that do not have GC have (contrary to popular belief, GC can offer better performance in many scenarios).
It does not matter if the class is static or not. It itself does not define state, the only thing is that it may not have been in an instance of it, but may have instances of other objects within it.
Dispose()
is interesting where it's needed, and has several questions about this (I think there is more without the tag ).
Pool of objects is a strong hint and .NET newer (2.1) already has it more or less ready for trivial situations. And you have additions like pool streams , just to stay in an example.
Using ref
on structs
Using Static is the worst thing you can do in terms of memory. When using Static you are telling the server that this variable is always available in memory because it is initialized as soon as the program starts.
What do I recommend?
Do not create variables to store values that will only be used once. Example:
int result = num1 + num2;
if(result<0)
{}
Can be summarized in
if((num1+num2)<0) {}
Another thing I recommend is using using () so that all the variables used within that block are collected by the garbage collector as soon as the code exits that block.