Reputation: 12979
I've been wondering this for a while, and Google hasn't provided me with the information I want. How fast does the casting process take? Does it depend on the number of fields an object has? Is it something to be avoided at all costs? Does it differ on x32, x64 and ARM machines?
Upvotes: 1
Views: 1473
Reputation: 22493
Casting is only for the compiler to issue you better warnings. At runtime casting has no performance hit. All objects are just objects. You send messages to those objects.
The runtime doesn't care what type you gave when you had a pointer to that object in your code. It will send the message no matter what.
For example:
NSArray *myString = [NSString stringWithFormat:@"Hello"];
NSNumber *longerString = [(NSString *)myString stringByAppendingString:@" World"];
NSLog(@"%@", longerString);
Will log Hello World
. You really give types to things so the compiler can check, but the runtime only knows that you're passing a message to an object. It will use the class of the object to look up the method to call from the message name, but it doesn't care what you typed at compile time.
You could have also done:
id myString = [NSString stringWithFormat:@"Hello"];
id longerString = [myString stringByAppendingString:@" World"];
NSLog(@"%@", longerString);
And the runtime will do the exact same thing, but the compiler will match up your types differently and generate warnings/errors based on different semantics (basically, does any object say it responds to this message).
Upvotes: 6