Faster Virtual Method Dispatch

Walter Bright newshound at digitalmars.com
Mon Apr 24 23:26:57 PDT 2006


Craig Black wrote:
> Hmmm.  I have glanced at the word count example many times but was not aware 
> of why it was faster in D until now.  Is it really the GC paradigm that 
> allows this performance?

Yes. It turns out to be very difficult for C++ to match it.

> I think I'm beginning to finally see some method 
> to the madness.  Perhaps I need to rethink my stance on GC a little.
> 
> It would seem then that GC can come out on top if there is a lot of sharing 
> of allocated memory e.g. multiple references to each object.  However, if 
> you are certain that there will be only a single reference to each object, 
> manual memory management should always outperform GC.  Am I on the right 
> track here?

Even in that case, gc can win. For example, for explicit memory 
allocation in the presence of exception handling, one has to carefully 
set up handlers that will delete any temporaries if an exception is thrown:

	S *p = new S();
	p->a = foo();
	bar(p);
	delete p;

What if foo() throws an exception? We've got a memory leak in p, so 
we've got to add code to fix that. Dealing with that is an endless 
source of bugs and tedium in C++. With gc, nothing needs to be added.

Another advantage of gc (that isn't implemented, but could be, in D's 
gc) is that allocated memory can be compacted. Compacting existing 
allocated memory means that allocating a new object is as easy as 
bumping a pointer, whereas the usual malloc algorithm requires searching 
a free list for a best match.

So, the obvious question then becomes, if gc is faster, why is Java 
slower than C++? (I know, lots of Java people will claim it really isn't 
slower <g>.) The reason is that Java's design requires a lot more 
objects to be allocated than in C++ - for example, you cannot aggregate 
arrays or other objects inside other objects, they have to be allocated 
separately. More objects allocated means lower performance.



More information about the Digitalmars-d mailing list