Re: Scope Best Practice
From: Diwakar R (diws_at_hotmail.com)
Date: 03/23/04
- Next message: Roger Helliwell: "Client-Server passing values problem. Caution: some HTML"
- Previous message: Glenn Lerner: "PrintPreview - display maximized"
- In reply to: John Baro: "Scope Best Practice"
- Next in thread: Jon Skeet [C# MVP]: "Re: Scope Best Practice"
- Reply: Jon Skeet [C# MVP]: "Re: Scope Best Practice"
- Messages sorted by: [ date ] [ thread ]
Date: Tue, 23 Mar 2004 09:45:46 +0530
Hi John,
I guess the answer to the problem lies in the question "What is the cost of
creating a new object versus the cost of maintaining it in memory?"
In the first case, the object is ready for GC once the loop is complete (
and hence it gets out of scope) this is light on the memory but has an
additional overhead of creating the object everytime.
In the second case, the object is not freed until the entire loop (100
times ) is completed.I think that it is ready for GC once the loop is over
even if it remains in scope because it is not being referenced anywhere
else. In this case, the memory is held by b for the entire duration of the
execution of the loop, but does saves on the time for creation.
Your best bet is to determine what is the nature of the object that you are
trying to reference ( as in is it a very heavy object requiring a lot of
time for creation) and what is the bottleneck in your application ( speed or
memory) and then choose the appropriate style.
I must also mention here that there is a middle path that one can take while
faced with this kind of problem. the solution lies in weak referencing where
in, the object is resurrected even if it is out of scope (but is not garbage
collected)
Hope that helps
-Diwakar
"John Baro" <johnb@NOSPAMmesware.com.au> wrote in message
news:XDO7c.120559$Wa.29622@news-server.bigpond.net.au...
> What are peoples thoughts on the following.
>
> for(int i = 0; i < 100; i++)
> {
> int b = 10;
> }
>
> or
>
> int b;
> for(int i = 0; i < 100; i++)
> {
> b = 10;
> }
>
> //b is not needed anywhere else.
>
> I would like to know whether people prefer to declare it outside scope and
> and not recreate it each time or the other way.
>
> Personally (There are much more knowledgeable people here than I) I prefer
> the first way as it keeps scope "tight".
> ie dont declare it where you dont need it.
>
> Cheers
> JB
>
>
- Next message: Roger Helliwell: "Client-Server passing values problem. Caution: some HTML"
- Previous message: Glenn Lerner: "PrintPreview - display maximized"
- In reply to: John Baro: "Scope Best Practice"
- Next in thread: Jon Skeet [C# MVP]: "Re: Scope Best Practice"
- Reply: Jon Skeet [C# MVP]: "Re: Scope Best Practice"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|