I'm curious about something regarding Objective-C. Say, the following line of code:
[obj method:argument];
Is it similar to Windows WinAPI sending a message provided via SendMessage? Or:
SendMessage(obj, method, argument, NULL);
I'm curious, because I'm quite proficient in C/C++ and Windows Win32, but I'm just learning Objective-C and I'm trying to understand its message passing system
. And namely, if it is similar to what SendMessage
does in Windows, and if so, such process of "calling" methods in Objective-C could be relatively slow for C/C++. Am I wrong?
Objective-C messaging is slightly different. Messages are not put in a queue (PostMessage) which is then serviced by the OS, they are performed directly on the relevant class (more or less like SendMessage), so they are generally a little faster than Windows messages, if you regard that most Windows messages are posted, not sent directly.
Invoking a method in Objective-C means that the name of the method is searched, which results in a unique identifier, a selector. This search can usually be done at compile time. The class is queried if it implements that selector, and if it does, the correspondent code is called, with the appropriate parameters. If it does not exist, an exception is thrown (see comments by Bryan Chen). If the instance on which the method is invoked is nil, it is simply ignored.
As you see, this is more or less similar to how Windows SendMessage works, but not entirely.
As the comment says, it is (quite a bit) slower than member function calling in C++, even slower than calling virtual functions.
More can be found in the Objective-C runtime reference.