2 ms·
I think this quote from a blog post [0] gives a pretty clear from the Objective-C perspective: I was thinking recently on the idea of “sending a message” ver
by wsc981 8y ago
I think this quote from a blog post [0] gives a pretty clear from the Objective-C perspective:
I was thinking recently on the idea of “sending a message” versus that of “calling
a method”. Those familiar with the capabilities of the Objective-C runtime understand
that there is a difference.
Most compiled languages refer to methods and functions internally as offsets. The
offset indicates that if one were to move a certain number of spaces in memory
from a designated starting point, then we would find the beginning of the
instructions that correspond to the desired function.
This has the advantage of being very fast. The starting point is known at compile-
time, and so to find the appropriate section of memory takes just a couple of
instructions. However, it has the disadvantage of being inflexible. This
is where most compiled languages differ from Objective-C
The Objective-C runtime maintains a list of all the methods and functions it knows
about. The list has two components per entry: the name of the method (known as
the method’s “selector”) and the location of the method in memory.
When an object attempts to “call a method”, it is really behaving quite differently.
When the code was compiled, the compiler translated the code [anObject
doMethod:aParameter]; into objc_msgSend(anObject, @selector(doMethod:),
aParameter); (basically. The actual behavior is slightly more complex but is all
explained in the documentation).
The objc_msgSend() function does a dynamic lookup. It knows the name of the method
it’s supposed to find (@selector(doMethod:)), and so it goes and looks up in its big
list where it can find what it’s supposed to do next.
This allows us to do some really interesting things. For example, we can modify this
list whenever we want. We can swap out values of the list, so that instead of
selector A executing the code for A, selector A might instead point to the code
for B. The runtime allows us to do some very powerful stuff.
The disadvantage is that this is (as you might imagine) slightly slower than directly
jumping to the appropriate section in code. However, the difference is
minute. Each message send takes just a couple nanoseconds longer than a regular
method call.
---
[0]: http://davedelong.tumblr.com/post/58428190187/an-observation-on-objective-c http://davedelong.tumblr.com/post/58428190187/an-observation...