Re: How does "new" work in a loop?
- From: Barry Kelly <barry.j.kelly@xxxxxxxxx>
- Date: Thu, 06 Jul 2006 22:45:46 +0100
"Matt" <matttelles@xxxxxxxxxxx> wrote:
So what is happening here? Is the memory being reused, or am I piling
up objects on the heap that will only go away when my program ends, or
am I creating a huge memory leak?
Unlikely that you are creating a memory leak. C# uses garbage
collection. When the object goes out of scope (in your case, the }
marked // for int i) the object is destroyed. The next time through
the loop, a new one is created.
It isn't freed immediately on every loop, or when it goes out of scope,
unless it's a value type (struct in C#). The GC kicks in on an as-needed
basis: memory pressure, repeated allocations, etc. That's one thing, and
is easy.
The other half of the story is resources. The GC isn't a resource
manager, so you shouldn't rely on it to manage things like file handles,
since it won't release them in a timely manner. That's why it's
important to use "using" with FileStream and other classes which
implement IDispose.
-- Barry
--
http://barrkel.blogspot.com/
.
- Follow-Ups:
- Re: How does "new" work in a loop?
- From: Matt
- Re: How does "new" work in a loop?
- From: Barry Kelly
- Re: How does "new" work in a loop?
- References:
- How does "new" work in a loop?
- From: Tony Sinclair
- Re: How does "new" work in a loop?
- From: Matt
- How does "new" work in a loop?
- Prev by Date: Re: How does "new" work in a loop?
- Next by Date: Re: Simple printing and graphics
- Previous by thread: Re: How does "new" work in a loop?
- Next by thread: Re: How does "new" work in a loop?
- Index(es):
Relevant Pages
|