Why Strings as Classes?

Michel Fortin michel.fortin at michelf.com
Tue Aug 26 18:11:28 PDT 2008


On 2008-08-26 13:25:40 -0400, Benji Smith <dlanguage at benjismith.net> said:

> I seem to remember reading something about the Objective-C compiler 
> maybe six or eight months ago talking about some of its optimization 
> techniques.
> 
> Obj-C uses a message-passing idiom, and all messages use dynamic 
> dispatch, since the list of messages an object can receive is not fixed 
> at compile-time.
> 
> If I remember correctly, this article said that the dynamic dispatch 
> expense only had to be incurred once, upon the first invocation of each 
> message type. After that, the address of the appropriate function was 
> re-written in memory, so that it pointed directly to the correct code. 
> No more dynamic dispatch. Although the message handlers aren't resolved 
> until runtime, once invoked, they'll always use the same target.
> 
> Or some thing like that.
> 
> It was an interesting read. I'll see if I can find it.

Hum, I believe you're talking about the cache for method calls. What 
Objective-C does is that it caches methods by selector in a lookup 
table. There is one such table for each class, and it gets populated as 
methods are called on that class.

Once a method is in the cache, it's very efficient to find where to 
branch: you take the selector's pointer and apply the mask to get value 
n, then branch on the method pointer from the nth bucket in the table.

All messages are passed by calling the objc_msgSend function. Here's 
how you can implement some of that in D:

	id objc_msgSend(id, SEL, ...) {
		auto n = cast(uint)SEL & id.isa.cache.mask;
		auto func = cast(id function(id, SEL, ...))id.isa.cache.buckets[n];
		if (func != null) {
			<set instruction pointer to func>
			// never returns, the function pointed by func returns instead
		}
		<find func pointer by other means, fill cache, etc.>
	}

I've read somewhere that it's almost as fast as virtual functions. 
While I haven't verified that, it's much more flexible: you can add 
functions at runtime to any class. That's how Objective-C allows you to 
add methods to classes you do not control and you can still override 
them in derived classes.

-- 
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/




More information about the Digitalmars-d mailing list