delegates vs functions => practical consequences

H. S. Teoh hsteoh at quickfur.ath.cx
Wed Apr 18 16:15:28 PDT 2012


On Wed, Apr 18, 2012 at 11:07:07PM +0200, Xan wrote:
> Hi,
> 
> I want to know what is most interesting for me: delegates or
> functions. I consulted sources but none say the practical
> consequences of such election.
> 
> What can I do and what can't I do with functions and delegates?
> Please, be didactics, I'm a newbee
[...]

The difference between functions and delegates is that functions do not
have access to variables and other stuff declared in their containing
lexical scope, whereas delegates do. For example:

	auto outer1(int[] args) {
		int x, y;

		return function(int z) {
			//z += args[0];	// Illegal: function has no
					// acceses to args of outer
					// function
			//return x;	// Illegal: function has no
					// local vars in outer function
			return z+1;	// OK, function can access its
					// own parameters
		}
	}

	auto outer2(int[] args) {
		int x, y;

		return delegate(int z) {
			z += args[0];	// OK, delegates contain a
					// "hidden pointer" to their
					// containing context
			z += x;		// This access includes outer
					// function's local variables
			return y+1;	// OK
		}
	}

In other words, delegates are much more flexible and powerful.

However, they come at a cost: function pointers are just a bare pointer
to some code, so they are very cheap. Delegates, on the other hand, are
"fat" pointers: in addition to the pointer to code, they also come with
a (hidden) pointer to the surrounding context of the delegate.

Furthermore, if you're returning a delegate (like in the example above),
this may cause some local variables in the outer function to be moved
out of the runtime stack into the heap, because otherwise the delegate's
context pointer will be pointing to invalid memory after the outer
function returns. This may have some speed/memory usage consequences.
Bare function pointers do not have this tradeoff.


T

-- 
Sometimes the best solution to morale problems is just to fire all of the unhappy people. -- despair.com


More information about the Digitalmars-d-learn mailing list