"stringWithString" vs "alloc ... initWithString ... autorelease"

I saw him claim that the following are "pretty much equivalent":

foo([NSString stringWithString:@"blah"])                       # version 1
foo([[[NSString alloc] initWithString:@"blah"] autorelease])   # version 2

Are these above actually literally equivalent or are there any subtle differences? What reasons do you prefer this or that?

+3
source share
4 answers

The two are functionally equivalent, but, like observing rpetrich, can work constantly, a little differently internally. It does not matter to you, use what seems more convenient to you. In addition, although there is a slight difference in performance, it hardly matters to your application in practice.

: . @ "foo", NSString. ; :

foo(@"blah")
+7

, "stringWithString", .

+8

objc_msgSend.

NSString , +alloc +allocWithZone:NSDefaultMallocZone()

+5

Methods such as + stringWithString: or + array are simply handy methods that always return objects with auto-implementation. They are mainly used to reduce the amount of code written for frequently created classes such as strings, arrays, dictionaries, numbers, etc. They strictly follow the basic rules of memory management, from which is deduced what I mentioned above.

+4
source

All Articles