Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have read a lot of .NET performance articles that describe Gen1,Gen2 garbage collection and objects surviving the generations.
Why does objects survives the collection?
What is pinning?
One reason you have multiple generations in a garbage collector is to avoid losing memory to fragmentation.
Every function call can mean the creation and deletion collection of multiple objects, and so the memory heap for your program tends to fragment very quickly. This leaves holes behind that aren't very usable. The result is that your program needs to be periodically de-fragmented, just like a hard disk. This is part of what happens during a collection.
When an object survives a collection, it is moved to a longer-lived generation on the theory that if it survived one collection it will probably survive others. Thus the later generations have less turn-over and don't fragment as much. This means your program spends less time overall juggling things around to clean up holes and wastes less memory. This is also an improvement over traditional memory management (malloc/free or new/delete), which left it up to the operating system to manage any memory fragmentation.
The reason an object survives collection is because there is something somewhere that is still "in scope" and holds a reference to that object. There are a few ways you can cause this to happen and then forget about the reference, so it is possible to "leak" memory in managed code.
Sometimes people are tempted to call GC.Collect() in an effort to get the garbage collector to clean something up. Perhaps they've discovered they have a leak, or think memory is becoming over-fragmented. You should resist those urges. While garbage collection in .Net is not perfect, is it very good, and it's almost certainly much better at cleaning up memory than you are. Odds are that if an object can and should be collected, it will be. Remember that calling GC.Collect() can actually make things worse by helping the garbage collector move objects up to a higher generation, and thus keeping them around for longer than they otherwise would be.
Instead, if you suspect you have a leak, look to your own code for something like a global or static variable that might hold a reference to a lot of other items. The only time you should call GC.Collect() is when you have information about the nature of the program that is not available to the garbage collector, and that's pretty rare as the GC knows every reference you've created.
"Pinning" is for when you need to pass an object to an unmanaged library. The garbage collector can move an object's physical location in memory, and so you need to "pin" it in one place or the pointer used by the unmanaged library could become invalid. A pinned object cannot be collected, and so you shouldn't pin an object for any longer than necessary.
http://blogs.msdn.com/maoni/ is a good resource.
Asking questions here helps too :)
For your questions:
Why do objects survive the collection:
Objects survive a collection when they are "live objects", or "Reachable objects". Reachable objects are objects where there is a reference to them from another object that is on:
The stack
The finalization queue
another object in a higher generation ( for example a Gen2 Object holding a reference to a Gen0 Object )
The handle table ( a data structure used by the CLR, and require a seperate post on its own:) )
What is Pinning:
Pinning means making sure the object doesn't move in memory. objects move in memory as a result of a compacting GC, you can create a GCHandle of typed pinned if you want to pin an object, pinning also happens automatically behind the sciene for objects that are passed to native code via PInvoke ( like strings that are passed as output, the internal buffer gets pinned during the call to PInvoke ).
Check out http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.gchandle.aspx for a good example about GCHandle.
Pinning is used to keep the garbage collector from relocating objects. It can hurt performance by restricting what the garbage collector can do. In general pinned objects should be pinned for as short as time as possible.
Related
This question already has answers here:
what is relation between GC, Finalize() and Dispose?
(3 answers)
Closed 4 years ago.
I'm using .Net 4.0 and i need to create a lot of images during my program works. As far as i understand images stored in LOH. Is Image.Dispose() method release memory in LOH? I tried to use profiler and i saw a lot of SOH cleans by GC, but memory usage of application still increase. And all memory releases only on if i call
GC.Collect();
GC.WaitForPendingFinalizers();
So it looks like dispose method of image doesn't release LOH memory.
IDisposable is a mechanism of managing the lifetime of unmanaged resources (either unmanaged memory or other things, like file handles). The LOH is for managed memory. So yes, calling Dispose will most likely do nothing at all to your managed heap usage since the two things have nothing in common.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Finalize vs Dispose
Dispose - This will free up the object memory and GC should be supperessed in this case.
Finalize - In case the object is not disposed and when then object goes out of the scope(I mean when the class goes out of the scope) GC will say Finalize to clean it up.
Destructor - Don't know. Can you explain difference b/w destructors and finalize ?
Dispose cannot free up memory. The Dispose() method releases or closes the unmanaged resources.
Finalize
It is used by the Garbage Collector implicitly to free the space.
Destructor
It is used to destroy the variable's value.
The destructor implicitly calls finalize, so it is sort of a pre-finalize.
See MSDN for more details. One important tidbit from that documentation:
Even with this explicit control over resources, the destructor becomes a safeguard to clean up resources if the call to the Dispose method failed.
Descrtuctor is in c++ and Finalizers are in .NET. Althought the way your represent a finalizer in C# code looks like a C++ descructor, but it's not the same and its behavior is different too.
Finalization is the last process that happens in .NET memory management. Disposing is the pattern one cleans up unmanaged memory. Remember that Dispose is the operation carried out manually or explicitly called basis, whereas finalizer is not. It's automatic by the run time.
You may wish to read this
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
C# memory leak?
Sorry if this is not the right place to post this, seeing as it's not strictly code related.
Basically, since the beginning of this work, a program which has worked flawlessly before has suddenly started throwing Out of Memory exceptions. After checking out the usage, I discovered the memory usage increases by a ridiculous 1mb per second! This happens on a part of the program that iterates over a collection, and calls many different methods - so it seems like these objects are staying in memory even after use.
What does this issue sound like to everyone else? I've been debugging the code, ensuring nothing's left open and all is disposed, but to no avail. I'm wondering if perhaps the .NET framework on the computer it runs from has become corrupt, and the garbage collection isn't running.
I plan to test on another computer later to hopefully prove this theory
Garbage collection will only clear up objects in the heap with no references left to them. Although you've ensured you're disposing everything it'll also be an idea to specifically null any of these references to objects after use.
Perhaps you can post the troublesome code?
Have a look at dotTrace tool. 10 days trial version is available.
Using it you can track what keeps the object reference to objects that should be removed from memory.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What and where are the stack and heap
There is a difference in C# between the heap and stack. I've just realized that I always thought that the stack is RAM and the heap is a hard drive. But now I'm not sure if it's correct. If it isn't, then what's is the difference if they are stored in one place?
"The stack" (or more precisely the call stack) is automatically managed memory (even in "unmanaged languages" like C): Local variables are stored on the stack in stack frames that also contain the procedures or functions arguments and the return address and maybe some machine-specific state that needs to be restored upon return.
Heap memory is that part of RAM (or rather: virtual address space) used to satisfy dynamic memory allocations (malloc in C).
Yet, in C# heap and stack usage is an implementation detail. In practice though, objects of reference type are heap-allocated; value type data can both be stored on the stack and on the heap, depending on the context (e.g. if it's part of an reference-type object).
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Should I make my classes immutable where possible?
I once read the book "Effective Java" by Joshua Bloch and he recommended to make all business objects immutable for various reasons. (for example thread safety)
Does this apply for C# too?
Do you try to make your objects immutable, so you have less problems when working with them?
Or is it not worth the inconvenience you have to create them?
The immutable Eric Lippert has written a whole series of blog posts on the topic. Part one is here.
Quoting from the earlier post that he links to:
ASIDE: Immutable data structures are the way of the future in C#. It is much easier to reason about a data structure if you know that it will never change. Since they cannot be modified, they are automatically threadsafe. Since they cannot be modified, you can maintain a stack of past “snapshots” of the structure, and suddenly undo-redo implementations become trivial. On the down side, they do tend to chew up memory, but hey, that’s what garbage collection was invented for, so don’t sweat it.
This is going to be more of an opinion type answer but...
I find that the ease of understanding a program, i.e. maintaining and debugging said application, is inversly proportional to the amount of stateful transitions that occur during the processing of each component. The less state I need to cart around in my head, the more focus I can pay attention to the logic within the algorithms as it is written.
Immutable objects are the central feature of functional programming; it has its own advantages and disadvantages. (E.g. linked lists are practically impossible to be immutable, but immutable objects make parallelism a piece of cake.) So as a comment on your post noted, the answer is "it depends".
Off the top of my head, I can't think of a reason for immutable objects making thread safe code somehow "better".
If I want an object to be thread safe, I will either put a lock around it or I will make a copy of it and update the reference once I'm done working on it. I typically wouldn't want a new object for every little change.
For me, immutable strings create more headaches for threading than it helps.
I actually went out of my way to make an "in-place" "ToUpper" using unsafe code isntead of the built in String.ToUpper(). It runs about 4 times faster and consumes 1/2 the peak memory.
Another nice benefit of immutable structures is that you can locally cache instances of them and reuse them across multiple threads without fear of unexpected behaviors as would be the case if they were mutable.
For instance, suppose you are using an external caching service such as memcached or Velocity or some other equally simplistic distributed hashtable service. You could just use the C# client library and call it good enough. However, that is being wasteful with resources given a short-lived context like a web request scenario. What you really want is to pull each object from the cache once and only once in your context.
The safest way to get this job done is to place a local hashtable in your process in front of the cache provider. On the first request for the cache key you'd pull down the serialized byte stream that represents the object you wish to use and store that byte stream in your local hashtable. On subsequent requests for the same cache key, just look up the byte stream in the local hashtable and deserialize the object to a new instance for each request. This is to prevent multiple redundant trips to the cache server node for the same information that assumedly has not changed over the lifetime of your context.
With immutable structures, you could deserialize the byte stream only once on the first request and get away with storing the deserialized instance in the hashtable instead of the byte stream and just share that one single immutable instance of your object. This obviously cuts down on deserialization penalties which can add up rather quickly if your consuming code is written in such a fashion that it does not care how many calls it makes to the caching provider, assuming the cache is faster than querying your underlying data store.
Perhaps this is more of a subjective answer, but it's a specific problem that can be solved uniquely by using immutable structures so I thought it was relevant to share.