473,795 Members | 2,630 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

When to use a garbage collector?

Hello,
traditionally, in C++, dynamically allocated memory has been
managed explicitly by calling "delete" in the application code.

Now, in addition to the standard library strings, containers, and
auto_ptrs, gurus suggest that may be better to use a reference-counted
smart pointer, or a garbage-collector.

But in which cases it is better to use one technique and in which cases
another? IOW, which is the design criterion?

And if, after having completed a working system, a technique would
result more performing than another, or better for other reasons, is it
advisable to change the memory management strategy of that working system?

--
Carlo Milanesi
http://digilander.libero.it/carlmila
Jun 27 '08 #1
46 2192
On 10 kesä, 18:30, Carlo Milanesi <carlo.milanesi .no.s...@libero .it>
wrote:
But in which cases it is better to use one technique and in which cases
another?
It's probably a question that has no answer. But I like the
old school delete, because it's transparent, you know exactly
what it's doing and when.
Jun 27 '08 #2
In article <48************ **********@news .tiscali.it>,
ca************* *******@libero. it says...

[ ... ]
Now, in addition to the standard library strings, containers, and
auto_ptrs, gurus suggest that may be better to use a reference-counted
smart pointer, or a garbage-collector.
_Some_ gurus -- there are others (who I think qualify as gurus) who are
opposed to the use of garbage collection to varying degrees, or at least
are of the view that its use should be restricted to specific
situations.
But in which cases it is better to use one technique and in which cases
another? IOW, which is the design criterion?
The cost of garbage collection varies based on the type of collector
used. Nearly every garbage collector has a "mark" phase, in which
"live" objects (i.e. those that are still accessible) are marked as
being in use. The cost of this phase is normally about linear on the
number of objects currently accessible to the program.

After that, different garbage collectors work in a number of different
ways. A copying collector copies all those live objects into a
contiguous space in memory, leaving another contiguous free space. This
makes allocations extremely cheap, and the cost of the collection as a
whole is also linear on the number of objects that are accessible.

Other collectors leave the "live" objects where they are, and create
free blocks of all the contiguous chunks of memory in the heap not
currently occupied by live objects. In this case, the cost of the
collection part tends to relate most closely to the number of contiguous
chunks of free memory in the heap.

On the other side, life isn't simple either. Manual memory management
tends to have costs associated most closely with the number of
allocations and frees used. This cost can be mitigated (drastically) in
certain cases, such as allocating a large number of objects of identical
size, or releasing a large number of objects all at the same, if the
allocator is written to allow them to be released together rather than
individually.

That only begins to tell the real story though: much of the cost of
manual allocation/deletion arises when objects are copied. A garbage
collector can (and does) keep track of different pointers that refer to
an object, and only deletes the object when all pointers that give
access to the object are gone. This makes it easy to keep a single
object, and create new pointers/references to that object whenever
needed.

With manual memory management, it's far more common to duplicate the
entire object, so each time the object is used, there's a separate
instance of the object to look at, and each instance has exactly one
owner that's responsible for deleting the object when it's no longer
needed. Allocating space to hold extra copies of the object, and copying
the relevant data into each copy, can take a considerable amount of
time. With a GC in place, you can usually avoid this copying by just
passing around pointers and everything shares access to that one object.
OTOH, when/if you need to copy the object anyway (e.g. if one copy will
be modified to become different from the other), this does little good.

As such, a tremendous amount depends upon things like: 1) what you're
allocating dynamically, 2) how you're using the dynamically allocated
objects, and 3) the degree to which objects you'd copy with manual
memory management can be shared in the presence of GC. All of these (and
more) depend on the application and design, not just the memory
management itself.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 27 '08 #3
On Jun 10, 11:30*am, Carlo Milanesi <carlo.milanesi .no.s...@libero .it>
wrote:
Hello,
* * *traditionally, in C++, dynamically allocated memory has been
managed explicitly by calling "delete" in the application code.

Now, in addition to the standard library strings, containers, and
auto_ptrs, gurus suggest that may be better to use a reference-counted
smart pointer, or a garbage-collector.

But in which cases it is better to use one technique and in which cases
another? IOW, which is the design criterion?

And if, after having completed a working system, a technique would
result more performing than another, or better for other reasons, is it
advisable to change the memory management strategy of that working system?
I almost always use smart pointers for objects. In any moderately
sized
system, the complexity of figuring out when to delete something is
just
not worth it. With smart pointers, you never have to delete.

Of course, memory managed *within* a class can be handled with raw
pointers.

So I don't see a real choie between using deletes and using smart
pointers
unless there is a special circumstance or platform.

We have yet to move or consider other forms of garbage collectors such
as that used in Java. Call me old fashioned ;).
Jun 27 '08 #4
On Jun 10, 9:42 am, Krice <pau...@mbnet.f iwrote:
On 10 kesä, 18:30, Carlo Milanesi <carlo.milanesi .no.s...@libero .it>
wrote:
But in which cases it is better to use one technique and in which cases
another?

It's probably a question that has no answer. But I like the
old school delete, because it's transparent, you know exactly
what it's doing and when.
I don't think so. Can you tell whether the delete here will be called:

void foo()
{
A * a = new A(/* ... */);
/* code that may throw today or some time in the future possibly
after some code change */
delete a;
}

To the OP: never deallocate resources explicitly in code. That would
not be "traditiona l," rather "developmental. " :) I used to do that
when I didn't know better. :/

Ali
Jun 27 '08 #5
On Jun 10, 12:03 pm, "AnonMail2...@g mail.com" <AnonMail2...@g mail.com>
wrote:
On Jun 10, 11:30 am, Carlo Milanesi <carlo.milanesi .no.s...@libero .it>
wrote:
I almost always use smart pointers for objects. In any moderately
sized
system, the complexity of figuring out when to delete something is
just
not worth it.
The problem is, that complex code hoping to figure out when to
'delete' an object may never be executed. The non-throwing lines of
code of today can suddenly start possibly throwing in the future by
code changes, and the explicit delete statement may never be executed.
Of course, memory managed *within* a class can be handled with raw
pointers.
Unfortunately that statement must be qualified further: you are
talking about classes that manage a single object, right? Because the
following class fits your description, but is not exception-safe and
cannot manage the memory it hopes to manage:

class HopefulManager
{
One * one_;
Two * two_;

public:

HopefulManager( )
:
one_(new One()),
two_(new Two()) // <- 1, <- 2
{
// some other code that may throw <- 3
}

~HopefulManager ()
{
delete two_;
delete one_;
}
};

The three places that may cause resource leaks are:

1) new may throw, one_'s object is leaked

2) Two() may throw, one_'s object is leaked

3) Any line is the constructor may throw, one_'s and two_'s objects
are leaked
So I don't see a real choie between using deletes and using smart
pointers
unless there is a special circumstance or platform.
What I said above is regardless of special circumstances or platforms.
Pure C++... :)

Ali
Jun 27 '08 #6
In article <ga************ *************** ****@ram.dialup .fu-berlin.de>,
ra*@zedat.fu-berlin.de says...
Jerry Coffin <jc*****@taeus. comwrites:
Allocating space to hold extra copies of the object, and copying
the relevant data into each copy, can take a considerable amount of
time. With a GC in place, you can usually avoid this copying by just
passing around pointers and everything shares access to that one object.
»There were two versions of it, one in Lisp and one in
C++. The display subsystem of the Lisp version was faster.
There were various reasons, but an important one was GC:
the C++ code copied a lot of buffers because they got
passed around in fairly complex ways, so it could be quite
difficult to know when one could be deallocated. To avoid
that problem, the C++ programmers just copied. The Lisp
was GCed, so the Lisp programmers never had to worry about
it; they just passed the buffers around, which reduced
both memory use and CPU cycles spent copying.«

<XN************ *****@newssvr13 .news.prodigy.c om>
Intentionally or otherwise, I suspect your post is likely to generate
fare more heat than light. Most of it is unsupported assertions, and
none of it is from anybody who appears to deserve the title of "guru",
at least with respect to C++ (and IMO, probably not in any other respect
either).

The first quote appears to be purely apocryphal -- an unsupported
statement from somebody posting under a pseudonym, about software of
unknown origin written by people of unknown skills.

Joel Spolsky spends a lot of time writing about software, but his
credentials seem questionable at best. In particular, I've seen nothing
to give a really strong indication that he's much of a programmer
(himself) at all.

IBM, of course, has a great deal of collective knowledge about
programming -- but the bit you quote is written with the specific intent
of promoting Java. It's been discussed here before, and at very best
it's misleading when applied to more than the very specific domain about
which it's written.

Finally we get yet another reference to Ian Joyner's "Critique of C++."
IMO, there should be something similar to Godwin's law relating to
anybody who quotes (any part of) this. First of all, it has nothing to
do with the C++ of today, or anytime in the last decade or more. As of
the first edition, some (a small fraction) was reasonably accurate about
the C++ of the time -- but the updates in his second and third editions
were insufficient to keep the relevant to the C++ of their times, and
the third edition still predates the original C++ standard by a couple
of years. With respect to the C++ of today, it varies from irrelevant to
misleading to downright false. Second, a great deal of it was misleading
when it was originally written. Third, nearly all the rest of it was
downright false when written.

When you get down to it, despite being umpteen pages long, the
criticisms in this paper that have at least some degree of validity with
respect to current C++ can be summarized as:

1) member functions should be virtual by default.
2) C++ should have Concepts [JVC: C++ 0x will].
3) Unified syntax for "." and "->" would be nice.
4) "static" is overloaded in too many (confusing) ways.
5) Modules would be better than headers.
6) Support for DbC would have some good points.

When you get down to it, however, it would be much easier to summarize
his critique in a single sentence: "C++ isn't Eiffel." Many of his
individual arguments aren't really supported at all -- they're simply
statements that C++ must be wrong because it's different from Eiffel.

Don't get me wrong: my previous statement that GC is favored for some
situations under some circumstances still stands -- but IMO, none of
these quotes provides any real enlightenment. Quite the contrary, the
quote from IBM means _almost_ nothing, and the other three (between
them) mean far less still.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 27 '08 #7
On Jun 10, 5:37 pm, acehr...@gmail. com wrote:
The problem is, that complex code hoping to figure out when to
'delete' an object may never be executed. The non-throwing lines of
code of today can suddenly start possibly throwing in the future by
code changes, and the explicit delete statement may never be executed.
Is there any chance that C++0x will give us mandatory checking of
throw() clauses in function definitions? That would enable the
compiler to warn about leaks when exceptions might happen between
calls to new and delete.
--
franl
Jun 27 '08 #8
On Jun 11, 12:54 am, Jerry Coffin <jcof...@taeus. comwrote:
In article <garbage-collection-20080610202...@ ram.dialup.fu-berlin.de>,
r...@zedat.fu-berlin.de says...
Jerry Coffin <jcof...@taeus. comwrites:
>Allocating space to hold extra copies of the object, and
>copying the relevant data into each copy, can take a
>considerable amount of time. With a GC in place, you can
>usually avoid this copying by just passing around pointers
>and everything shares access to that one object.
»There were two versions of it, one in Lisp and one in
C++. The display subsystem of the Lisp version was faster.
There were various reasons, but an important one was GC:
the C++ code copied a lot of buffers because they got
passed around in fairly complex ways, so it could be quite
difficult to know when one could be deallocated. To avoid
that problem, the C++ programmers just copied. The Lisp
was GCed, so the Lisp programmers never had to worry about
it; they just passed the buffers around, which reduced
both memory use and CPU cycles spent copying.«
<XNOkd.7720$zx1 .5...@newssvr13 .news.prodigy.c om>
Intentionally or otherwise, I suspect your post is likely to
generate fare more heat than light. Most of it is unsupported
assertions, and none of it is from anybody who appears to
deserve the title of "guru", at least with respect to C++ (and
IMO, probably not in any other respect either).
You noticed that too.
The first quote appears to be purely apocryphal -- an
unsupported statement from somebody posting under a pseudonym,
about software of unknown origin written by people of unknown
skills.
The first quote is probably the one which does correspond most
to practical reality; I seem to recall a similar statement being
made by Walter Bright (who certainly does qualify as a C++
guru). But of course, it doesn't have to be that way.
Joel Spolsky spends a lot of time writing about software, but
his credentials seem questionable at best. In particular, I've
seen nothing to give a really strong indication that he's much
of a programmer (himself) at all.
Another case of "those who can, do; those who can't teach (or
write articles)".
IBM, of course, has a great deal of collective knowledge about
programming -- but the bit you quote is written with the
specific intent of promoting Java. It's been discussed here
before, and at very best it's misleading when applied to more
than the very specific domain about which it's written.
Finally we get yet another reference to Ian Joyner's "Critique
of C++." IMO, there should be something similar to Godwin's
law relating to anybody who quotes (any part of) this. First
of all, it has nothing to do with the C++ of today, or anytime
in the last decade or more. As of the first edition, some (a
small fraction) was reasonably accurate about the C++ of the
time -- but the updates in his second and third editions were
insufficient to keep the relevant to the C++ of their times,
and the third edition still predates the original C++ standard
by a couple of years. With respect to the C++ of today, it
varies from irrelevant to misleading to downright false.
Second, a great deal of it was misleading when it was
originally written. Third, nearly all the rest of it was
downright false when written.
When you get down to it, despite being umpteen pages long, the
criticisms in this paper that have at least some degree of
validity with respect to current C++ can be summarized as:
1) member functions should be virtual by default.
Which is just wrong, at least from a software engineering point
of view.
2) C++ should have Concepts [JVC: C++ 0x will].
3) Unified syntax for "." and "->" would be nice.
I don't think I agree with this one, either.
4) "static" is overloaded in too many (confusing) ways.
The price we pay for C compatibility.
5) Modules would be better than headers.
I don't think anyone could disagree with that one. Of course,
just about everyone has a different definition of what they mean
by "modules".
6) Support for DbC would have some good points.
Interestingly, I think that C++ today has the best support of
any language, although it's not automatic, and many programmers
fail to use it.
When you get down to it, however, it would be much easier to
summarize his critique in a single sentence: "C++ isn't
Eiffel." Many of his individual arguments aren't really
supported at all -- they're simply statements that C++ must be
wrong because it's different from Eiffel.
Don't get me wrong: my previous statement that GC is favored
for some situations under some circumstances still stands --
but IMO, none of these quotes provides any real enlightenment.
Quite the contrary, the quote from IBM means _almost_ nothing,
and the other three (between them) mean far less still.
I don't think that there is complete consensus among the gurus
as to when garbage collection would be appropriate. I would be
very suspicious, however, of anyone who claimed that it is
always appropriate, or never appropriate. That it's not
available in the standard toolkit is a definite flaw in the
language, but requiring it to be used in every case would
probably be even worse (but I don't think anyone has ever
proposted that).

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #9
Carlo Milanesi <ca************ ********@libero .itwrites:
Hello,
traditionally, in C++, dynamically allocated memory has been
managed explicitly by calling "delete" in the application code.

Now, in addition to the standard library strings, containers, and
auto_ptrs, gurus suggest that may be better to use a reference-counted
smart pointer, or a garbage-collector.

But in which cases it is better to use one technique and in which
cases another? IOW, which is the design criterion?
Reference counted smart pointers: never. They leak memory as soon as
you have bidirectionnal associations or cycles in your data
structures.

Garbage collectors: always. There are even real-time garbage
collectors, if you have real-time constraints.

And if, after having completed a working system, a technique would
result more performing than another, or better for other reasons, is
it advisable to change the memory management strategy of that working
system?
Well, usually garbage collectors give better performance.
http://www.jwz.org/doc/gc.html
But of course it depends on the application and datasets. It might be
easier to change the garbage collection strategy, selecting one more
adapted to the application, than to change the application to use
another memory management style. On the other hand, if you write your
code with reference counting, it is easy enough to disable reference
counting and fall back to garbage collection.

--
__Pascal Bourguignon__
Jun 27 '08 #10

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

Similar topics

1
2338
by: Bob | last post by:
Are there any known applications out there used to test the performance of the .NET garbage collector over a long period of time? Basically I need an application that creates objects, uses them, and then throws them away and then monitors the garbage collection and store statistics on it, preferably in C#. I want to know what is the longest period of time that an application may lock up while garbage collection is processing. Thanks!
4
2043
by: Pedro Miguel Carvalho | last post by:
Greetings. I'm creating a project that as a intricate relation between object kind of like a set where each object in the set can be connect to a subset of object of the set and objects not in the set can connect to objects in the set. Every object inherits a interface to allow for a mark and sweep garbage collector (GC) and my implementation works correctly and efficiently but only in a single thread. How can I garbage collect in a...
10
2053
by: pachanga | last post by:
The Hans-Boehm garbage collector can be successfully used with C and C++, but not yet a standard for C++.. Is there talks about Garbage Collector to become in the C++ standard?
6
5171
by: Ana | last post by:
Hi! I have problems with the following scenario: My application is developed using C# under .NET. It must run on all Windows versions starting from Windows 98. The user must open different documents (txt, MS Office files, pdf, pictures,…) from inside my app. It must start the file with the adequate external program (Notepad, MS Office programs, Acrobat Reader, some Picture viewer,... ) and be notified when this programs closes the...
4
1699
by: R. MacDonald | last post by:
Hello, all, I have a .NET application (VB) that passes the address of a delegate to unmanaged code in a DLL. The unmanaged code then uses the delegate as a call-back. This seems to work fine, but now I am worried about garbage collection. I am concerned that the location of the delegate might be altered as a result of other (unused) objects being garbage collected. This would probably cause undesirable results when the unmanaged DLL...
13
3817
by: Mingnan G. | last post by:
Hello everyone. I have written a garbage collector for standard C++ application. It has following main features. 1) Deterministic Finalization Providing deterministic finalization, the system can manage resources as well as objects. The programming style is clear and easy, conforming to RAII (Resource Acquisition Is Initialization) idiom of C++ programmers. The memory usage is very efficient, acyclic garbage is
44
8275
by: Smokey Grindle | last post by:
I have a list box on my form, but I need to databind it to a data table that is a private member of the form's class... so I basically have Public Class MyForm priate m_MyTable as new datatable End Class now where would I properly dispose of this? In the finalize method? I am loading the data for the table in a subroutine that is executed at form load, of course all the commands tied to it are wrapped in using blocks, but
350
11907
by: Lloyd Bonafide | last post by:
I followed a link to James Kanze's web site in another thread and was surprised to read this comment by a link to a GC: "I can't imagine writing C++ without it" How many of you c.l.c++'ers use one, and in what percentage of your projects is one used? I have never used one in personal or professional C++ programming. Am I a holdover to days gone by?
0
2197
by: raylopez99 | last post by:
I ran afoul of this Compiler error CS1612 recently, when trying to modify a Point, which I had made have a property. It's pointless to do this (initially it will compile, but you'll run into problems later). Apparently Point is a struct, a value type, and it does not behave like a classic structure (in my mind's eye, and see below). Traditionally I think of a classic structure as simply an object where every member is public. But with...
0
9519
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10438
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10214
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10164
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9042
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6780
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5437
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2920
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.