Re: How does "new" work in a loop?
- From: "Matt" <matttelles@xxxxxxxxxxx>
- Date: 7 Jul 2006 06:33:32 -0700
Barry Kelly wrote:
"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.
Yes, I know this. The OP was a C++ programmer, I was giving it to him
in C++ context. GC is deterministic, it will kick in when it makes
sense
to kick in.
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.
True and a good point. I was just explaining why it wasn't a memory
leak,
but your explanation is better for this purpose.
Thanks
Matt
.
- Follow-Ups:
- Re: How does "new" work in a loop?
- From: Jon Skeet [C# MVP]
- 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
- Re: How does "new" work in a loop?
- From: Barry Kelly
- How does "new" work in a loop?
- Prev by Date: Re: Clever string replacement in collection
- Next by Date: Mdi bug ?
- 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
|