473,378 Members | 1,343 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

"using" vs "= null" and object lifetime

Hi,

Lately i've been (and still am) fixing some memory leaks problems in the project i just took over
when i got this new job. Among the other issues i've noticed that for localy created objects it
makes difference to explicitly put them to null after working with them is done - it somehow makes
the GC collect them sooner, like here:

void SomeFunc()
{
MyClass c = new MyClass();
c.CallSomeOtherFunc();
c = null;
}

If i don't put "c" to null time to get it collected is way longer than if i explicitly dereference
the object. It's really strange, as it's obvoius that object's lifetime is limited by body of
"SomeFunc". But anyway, my question is: is there any difference in the first example compared to this:

void SomeFunc()
{
using (MyClass c = new MyClass())
{
c.CallSomeOtherFunc();
}
}

The second way looks nicer for me and avoids forgetting to explicitly dereference the object,
but i'm not sure if this second case is being treated the same way as the first one.

Any suggestions/ideas would be highly appreciated!

Thnak you,
Andrey
Nov 16 '05 #1
14 3117
On Thu, 17 Feb 2005 10:02:52 -0500, MuZZy wrote:
Lately i've been (and still am) fixing some memory leaks problems in the project i just took over
when i got this new job. Among the other issues i've noticed that for localy created objects it
makes difference to explicitly put them to null after working with them is done - it somehow makes
the GC collect them sooner, like here:

void SomeFunc()
{
MyClass c = new MyClass();
c.CallSomeOtherFunc();
c = null;
}

If i don't put "c" to null time to get it collected is way longer than if i explicitly dereference
the object. It's really strange, as it's obvoius that object's lifetime is limited by body of
"SomeFunc". But anyway, my question is: is there any difference in the first example compared to this:

void SomeFunc()
{
using (MyClass c = new MyClass())
{
c.CallSomeOtherFunc();
}
}

The second way looks nicer for me and avoids forgetting to explicitly dereference the object,
but i'm not sure if this second case is being treated the same way as the first one.


Your second case is not the same as the first. Another way to write the
second would be:

void SomeFunc()
{
MyClass c = new MyClass()
try
{
c.CallSomeOtherFunc();
}
finally
{
c.Dispose();
}
}

So in your first example you are setting c to null before it goes out of
scope. In your second example you are not setting c to null, but you are
guaranteeing that c.Dispose() will be called no matter what happens.
--
Tom Porterfield
Nov 16 '05 #2
Andrey,

See inline:
Lately i've been (and still am) fixing some memory leaks problems in the
project i just took over when i got this new job. Among the other issues
i've noticed that for localy created objects it makes difference to
explicitly put them to null after working with them is done - it somehow
makes the GC collect them sooner, like here:

void SomeFunc()
{
MyClass c = new MyClass();
c.CallSomeOtherFunc();
c = null;
}
This depends on how it is compiled. If you are compiling in debug mode,
then yes, it will make it GC faster (although how much faster is
questionable since c would have been released very quickly afterwards, due
to exiting the method). The reason for this is that code compiled in debug
mode will not have references released when they are no longer used. When
compiled for release mode, however, you are actually ^extending^ the
lifetime of your object with the "c = null" assignment. If the statement
was not there, the compiler would realize that the object pointed to by c is
no longer needed after the call to CallSomeOtherFunc (unless the reference
pointed to by c is stored somewhere else in the call to CallSomeOtherFunc),
and then set it to null, allowing it to become eligible for GC.

However, with the "c = null" statement, the compiler realizes (although
I don't know if agressive optimizations here can pick it up) that it is
needed for another call, and the object pointed to by c isn't made eligible
until ^after^ the assignment.
If i don't put "c" to null time to get it collected is way longer than if
i explicitly dereference the object. It's really strange, as it's obvoius
that object's lifetime is limited by body of "SomeFunc".
This isn't true. GCs are not pre-determined. Why a GC occurs very
quickly in one run of the app as opposed to very late in another run of the
app is not easily determinable. There are other factors outside your
application which can force a GC as well. The timing of one GC in one run
of the app vs a GC of another run in an app means very little.
But anyway, my question is: is there any difference in the first example
compared to this:

void SomeFunc()
{
using (MyClass c = new MyClass())
{
c.CallSomeOtherFunc();
}
}

The second way looks nicer for me and avoids forgetting to explicitly
dereference the object,
but i'm not sure if this second case is being treated the same way as the
first one.
This is a separate issue completely. Just because you implement
IDispose, it doesn't mean that the object doesn't need to be GCed anymore.
If you have IDispose, it means that you need to manage the lifetime of the
object in some way by calling the Dispose method on the implementation of
IDispose. There are usually two reasons you implement IDispose.

The first, and most common, is because the instance is holding on to
some unmanaged resource, and you need to release it as soon as possible.
When implementing IDispose in this scenario, you also need to implement a
finalizer (destructor, although the term is incorrect, IMO). The finalizer
is meant to be a safeguard if people don't call Dispose. It will basically
release the unmanaged resource if it hasn't been done already.

Finalization is an expensive process. The object is basically
ressurected and placed in a finalization queue, and then has the finalizer
executed. If Dispose is called on an object, it doesn't need to be
finalized, which is why you see a call to GC.SuppressFinalize in the
implementation of Dispose, and not the finalizer itself. Since the
finalizer and Dispose do the same thing, if Dispose is called, you can
effectively tell the GC to not finalize you, and avoid that costly overhead.

However, even if you say that you are going to suppress finalization,
the object still has to be GCed. The process of having the memory reclaimed
still has to occur on this object, even when Dispose is called. However,
it's something you really don't care about, because it's just memory, and
you gave up control of that (for the most part) by agreeing to run in the
CLR (that's the purpose of the GC, to worry about these things, not yours).

Suppressing finalization only means the finalizer will not be called, it
doesn't mean that the object has been GCed.

The second reason to use IDispose is because you need some deterministic
finalization to take place. For example, you might always need some
variable set back after an operation in a method. In this case generating a
class which implements IDisposable might be a good idea, since you can
revert the variable back when the using block is exited (instead of having
to explicitly remembering to code a try/catch/finally block).

In your case, you fall into the first category for using IDispose.
Using the using statement will be important, if you actually have an
unmanaged resource you are holding on to. If you do not, and it is just a
regular class, then using the using statement will not work, and
implementing IDispose will not help either.

Hope this helps.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

Any suggestions/ideas would be highly appreciated!

Thnak you,
Andrey

Nov 16 '05 #3
Tom Porterfield wrote:
On Thu, 17 Feb 2005 10:02:52 -0500, MuZZy wrote:

Lately i've been (and still am) fixing some memory leaks problems in the project i just took over
when i got this new job. Among the other issues i've noticed that for localy created objects it
makes difference to explicitly put them to null after working with them is done - it somehow makes
the GC collect them sooner, like here:

void SomeFunc()
{
MyClass c = new MyClass();
c.CallSomeOtherFunc();
c = null;
}

If i don't put "c" to null time to get it collected is way longer than if i explicitly dereference
the object. It's really strange, as it's obvoius that object's lifetime is limited by body of
"SomeFunc". But anyway, my question is: is there any difference in the first example compared to this:

void SomeFunc()
{
using (MyClass c = new MyClass())
{
c.CallSomeOtherFunc();
}
}

The second way looks nicer for me and avoids forgetting to explicitly dereference the object,
but i'm not sure if this second case is being treated the same way as the first one.

Your second case is not the same as the first. Another way to write the
second would be:

void SomeFunc()
{
MyClass c = new MyClass()
try
{
c.CallSomeOtherFunc();
}
finally
{
c.Dispose();
}
}

So in your first example you are setting c to null before it goes out of
scope. In your second example you are not setting c to null, but you are
guaranteeing that c.Dispose() will be called no matter what happens.


Thank you!
So if i'm more concerned about shorter object lifetime, i'd rather do this:

void SomeFunc()
{
MyClass c = new MyClass()
c.CallSomeOtherFunc();
c.Dispose();
c = null;
}

than use "using"?
Right?
Nov 16 '05 #4
Hello

In a Debug build, the object will not be eligible for garbage collection
until the function returns or you set the object reference to null. In a
Release build, the JIT compiler makes some optimizations, so that the
variable is eligible for garbage collection as soon as it is no longer
needed, even if the function call is still active. So in a release build you
don't need to set the object reference to null after you finish using it
because CLR and JIT will take care of that.

As for the using statement, its use is not to make GC collect the memory for
the object. It is used so that any resource (such as db connections, file
handles, GDI object, native memory, etc) held by the object is released
soon, even if the GC collects it at a later time. It can be used only with
objects that implement IDisposable, and it makes sure that the Dispose
method gets called after you finish using the object.

Best regards,
Sherif

"MuZZy" <le*******@yahoo.com> wrote in message
news:Hs********************@comcast.com...
Hi,

Lately i've been (and still am) fixing some memory leaks problems in the project i just took over when i got this new job. Among the other issues i've noticed that for localy created objects it makes difference to explicitly put them to null after working with them is done - it somehow makes the GC collect them sooner, like here:

void SomeFunc()
{
MyClass c = new MyClass();
c.CallSomeOtherFunc();
c = null;
}

If i don't put "c" to null time to get it collected is way longer than if i explicitly dereference the object. It's really strange, as it's obvoius that object's lifetime is limited by body of "SomeFunc". But anyway, my question is: is there any difference in the first example compared to this:
void SomeFunc()
{
using (MyClass c = new MyClass())
{
c.CallSomeOtherFunc();
}
}

The second way looks nicer for me and avoids forgetting to explicitly dereference the object, but i'm not sure if this second case is being treated the same way as the first one.
Any suggestions/ideas would be highly appreciated!

Thnak you,
Andrey

Nov 16 '05 #5
Thanks guys, now it's more clear for me!
MOst important things you've told are that it makes sence to use "using" only if object has
IDisposable interface, and second, that debug mode slighty differs from Release mode in terms of
memory management - i shouldn't explcitly dereference objects in Release mode.

MuZZy wrote:
Hi,

Lately i've been (and still am) fixing some memory leaks problems in the
project i just took over when i got this new job. Among the other issues
i've noticed that for localy created objects it makes difference to
explicitly put them to null after working with them is done - it somehow
makes the GC collect them sooner, like here:

void SomeFunc()
{
MyClass c = new MyClass();
c.CallSomeOtherFunc();
c = null;
}

If i don't put "c" to null time to get it collected is way longer than
if i explicitly dereference the object. It's really strange, as it's
obvoius that object's lifetime is limited by body of "SomeFunc". But
anyway, my question is: is there any difference in the first example
compared to this:

void SomeFunc()
{
using (MyClass c = new MyClass())
{
c.CallSomeOtherFunc();
}
}

The second way looks nicer for me and avoids forgetting to explicitly
dereference the object,
but i'm not sure if this second case is being treated the same way as
the first one.

Any suggestions/ideas would be highly appreciated!

Thnak you,
Andrey

Nov 16 '05 #6
On Thu, 17 Feb 2005 10:24:18 -0500, MuZZy wrote:
So if i'm more concerned about shorter object lifetime, i'd rather do this:

void SomeFunc()
{
MyClass c = new MyClass()
c.CallSomeOtherFunc();
c.Dispose();
c = null;
}

than use "using"?
Right?


No, see Nicholas' reply on why this doesn't guarantee a shorter object
lifetime, and in fact might lengthen it.
--
Tom Porterfield
Nov 16 '05 #7
MuZZy <le*******@yahoo.com> wrote:
Lately i've been (and still am) fixing some memory leaks problems in
the project i just took over when i got this new job. Among the other
issues i've noticed that for localy created objects it makes
difference to explicitly put them to null after working with them is
done - it somehow makes the GC collect them sooner, like here:

void SomeFunc()
{
MyClass c = new MyClass();
c.CallSomeOtherFunc();
c = null;
}

If i don't put "c" to null time to get it collected is way longer
than if i explicitly dereference the object.


In release, or only in debug? I'd be very surprised if it made any
difference in release mode.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #8
Nicholas Paldino [.NET/C# MVP] <mv*@spam.guard.caspershouse.com> wrote:
void SomeFunc()
{
MyClass c = new MyClass();
c.CallSomeOtherFunc();
c = null;
}


This depends on how it is compiled. If you are compiling in debug mode,
then yes, it will make it GC faster (although how much faster is
questionable since c would have been released very quickly afterwards, due
to exiting the method). The reason for this is that code compiled in debug
mode will not have references released when they are no longer used.


Are you sure it's a case of how it's compiled? I was under the
impression that it was how it was being *run* - which would make sense,
as if you're not running in the debugger, you don't need to know the
value of c after the last use even if the debug symbols are present.

When I get the chance I may test this in each configuration just to see
what happens...

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #9
"MuZZy" <le*******@yahoo.com> wrote in message
news:fs********************@comcast.com...
Thanks guys, now it's more clear for me!
MOst important things you've told are that it makes sence to use "using"
only if object has IDisposable interface, and second, that debug mode
slighty differs from Release mode in terms of memory management - i
shouldn't explcitly dereference objects in Release mode.
Don't confine that last statement to just Release mode. There's no real need
to dereference objects in almost all circumstances.

MuZZy wrote:
Hi,

Lately i've been (and still am) fixing some memory leaks problems in the
project i just took over when i got this new job. Among the other issues
i've noticed that for localy created objects it makes difference to
explicitly put them to null after working with them is done - it somehow
makes the GC collect them sooner, like here:

void SomeFunc()
{
MyClass c = new MyClass();
c.CallSomeOtherFunc();
c = null;
}

If i don't put "c" to null time to get it collected is way longer than if
i explicitly dereference the object. It's really strange, as it's obvoius
that object's lifetime is limited by body of "SomeFunc". But anyway, my
question is: is there any difference in the first example compared to
this:

void SomeFunc()
{
using (MyClass c = new MyClass())
{
c.CallSomeOtherFunc();
}
}

The second way looks nicer for me and avoids forgetting to explicitly
dereference the object,
but i'm not sure if this second case is being treated the same way as the
first one.

Any suggestions/ideas would be highly appreciated!

Thnak you,
Andrey

Nov 16 '05 #10
Jon Skeet [C# MVP] wrote:
MuZZy <le*******@yahoo.com> wrote:
Lately i've been (and still am) fixing some memory leaks problems in
the project i just took over when i got this new job. Among the other
issues i've noticed that for localy created objects it makes
difference to explicitly put them to null after working with them is
done - it somehow makes the GC collect them sooner, like here:

void SomeFunc()
{
MyClass c = new MyClass();
c.CallSomeOtherFunc();
c = null;
}

If i don't put "c" to null time to get it collected is way longer
than if i explicitly dereference the object.

In release, or only in debug? I'd be very surprised if it made any
difference in release mode.


I haven't tested that in Release mode - just Debug.
Now having read all the responces i fnally got the whole picture i hope:)
Nov 16 '05 #11
Surely assigning an object to null at the end of a method will be optimized
out during compilation?

Or am I trying to second guess what goes on during compliation :)

Ollie
But there again how can I second guess what the compile or
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Nicholas Paldino [.NET/C# MVP] <mv*@spam.guard.caspershouse.com> wrote:
> void SomeFunc()
> {
> MyClass c = new MyClass();
> c.CallSomeOtherFunc();
> c = null;
> }


This depends on how it is compiled. If you are compiling in debug
mode,
then yes, it will make it GC faster (although how much faster is
questionable since c would have been released very quickly afterwards,
due
to exiting the method). The reason for this is that code compiled in
debug
mode will not have references released when they are no longer used.


Are you sure it's a case of how it's compiled? I was under the
impression that it was how it was being *run* - which would make sense,
as if you're not running in the debugger, you don't need to know the
value of c after the last use even if the debug symbols are present.

When I get the chance I may test this in each configuration just to see
what happens...

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #12
Ollie Riches <ol**********@phoneanalyser.net> wrote:
Surely assigning an object to null at the end of a method will be optimized
out during compilation?
Not during C#->IL compilation.
Or am I trying to second guess what goes on during compliation :)


Yup...

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #13
Jon Skeet [C# MVP] <sk***@pobox.com> wrote:
This depends on how it is compiled. If you are compiling in debug mode,
then yes, it will make it GC faster (although how much faster is
questionable since c would have been released very quickly afterwards, due
to exiting the method). The reason for this is that code compiled in debug
mode will not have references released when they are no longer used.


Are you sure it's a case of how it's compiled? I was under the
impression that it was how it was being *run* - which would make sense,
as if you're not running in the debugger, you don't need to know the
value of c after the last use even if the debug symbols are present.

When I get the chance I may test this in each configuration just to see
what happens...


I've just tested this, and Nick's absolutely right. In fact, unlike
some other optimisations, this one looks like it's at the IL level,
rather than just being dependent on whether or not there's a pdb file
present. Here's the test program I used:

using System;

class Test
{
~Test()
{
Console.WriteLine ("Finalized");
}

static void Main()
{
Test t = new Test();

GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine ("After first collect");
t = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine ("After second collect");
}
}

When compiled in non-debug mode (or in debug "pdb only" mode) the
results are:

After first collect
Finalized
After second collect

When compiled in full debug mode, the results are:
Finalized
After first collect
After second collect

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #14
Jon Skeet [C# MVP] <sk***@pobox.com> wrote:
When compiled in non-debug mode (or in debug "pdb only" mode) the
results are:

After first collect
Finalized
After second collect

When compiled in full debug mode, the results are:
Finalized
After first collect
After second collect


Those should be the other way round, of course. Doh! Don't you just
hate it when you spot something wrong at the moment that the articles
just been posted?

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Pablo J Royo | last post by:
Hello: i have a function that reads a file as an argument and returns a reference to an object that contains some information obtained from the file: FData &ReadFile(string FilePath); But ,...
13
by: Don Vaillancourt | last post by:
What's going on with Javascript. At the beginning there was the "undefined" value which represented an object which really didn't exist then came the null keyword. But yesterday I stumbled...
4
by: Peter Hemmingsen | last post by:
Hi, I have a dotnet object (implemented in mc++ and used in c#) which have a property called "Info". The Info property is also a dotnet object (implemented in mc++). In the constructor of the...
7
by: Clint Herron | last post by:
Howdy! I posted this question on CSharpCorner.com, but then realized I should probably post it on a more active newsgroup. This will be my only cross-post. I'm creating a game engine, and...
5
by: Dave | last post by:
What is the benefit of using "as" vs the other? HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("http://www.contoso.com/"); vs. HttpWebRequest myReq...
5
by: rengeek33 | last post by:
I am building a SQL statement for Oracle and need one part of it to read: , myvar = null, myvar2 = "1", myvar3 = "0", myvar4 = null, etc. I am constructing this string using the String...
15
by: arnuld | last post by:
-------- PROGRAMME ----------- /* Stroustrup, 5.6 Structures STATEMENT: this programmes *tries* to do do this in 3 parts: 1.) it creates a "struct", named "jd", of type "address". 2. it...
10
by: Angel Tsankov | last post by:
Hello! Is the following code illformed or does it yield undefined behaviour: class a {}; class b {
0
by: Luis Zarrabeitia | last post by:
Quoting Joe Strout <joe@strout.net>: But, at least in C++, its really confusing. The 'static' word is reservedon C++ for more than one meaning, but I'll agree that it is a C++ problem and not a...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.