Is SendMessage() or GetComponent() faster?

Hi all, this is just a quick optimization question. Basically which of the following is faster, if there is a difference:

public GameObject obj;

// option 1
obj.SendMessage("methToCall");

// option 2
obj.GetComponent<respectiveScript>().methToCall();

All help appreciated.

SendMessage is absurdly much slower.

SendMessage has to go through every script, look for a method with the same name using string comparrison (slower), and call it. The GetComponent finds the script through type comparrison (faster), and calls the method directly.

GetComponent can also be cached, which is the fastest alternative:

//option 3
respectiveScript myScript;

void Start() {
    myScript = obj.GetComponent<respectiveScript>();
}

...

    myScript.methToCall();

There’s also some big differences in functionality. SendMessage will send the call to every monobehaviour - which means that if you much later add a new script with a method that’s named the same thing to your gameobject, that method will be called too.

In addition, you can only use a single parameter in SendMessage, so you can’t call methods like these:

void MyMethod(string stringArg, int intArg) { … }

Finally, if you’re writing code with an IDE (MonoDevelop or Visual Studio), you can rename methods with the refactor->rename functionality. That allows you to change the name of a method, and have the same method be renamed wherever you use it. If you use sendMessage to call that method, this won’t work, as the compiler doesn’t “see” that you’re referencing that method if it’s inside a string.

Short version: never use SendMessage, it’s horrible.