問題描述
Obj‑C:遞歸:在堆棧上創建新對像或使用可變性 (Obj‑C: Recursion: Making new objects on stack or use mutability)
My question is this. In the code you see bellow, my second param is a NSString*
and as I recursively get objects from the array and adds them to the buildDescription
parameter I use the method stringByAppendingFormat
which as I understand ‑ creates a new object on the heap. Would it be better if I had an mutable string in the parameter and then use some other methods to append the new variables? as all objects in Obj‑C are created on the heap, is this the preferred way of doing recursion, and what are the benefits for both approaches? of course It demands less memory just passing pointers to an mutable object.
+ (NSString *)makeDescriptionRecur:(NSMutableArray *)stack: (NSString *) buildDescription
{
id topOfStack = [stack lastObject];
if (topOfStack) [stack removeLastObject];
if ([topOfStack isKindOfClass:[NSNumber class]])
{
return [self makeDescriptionRecur:stack:
[buildDescription stringByAppendingFormat:@"%@ ", topOfStack]];
} else if ([topOfStack isKindOfClass:[NSString class]]) {
‑‑‑‑‑
參考解法
方法 1:
Would it be better if I had an mutable string in the parameter and then use some other methods to append the new variables?
At least that wouldn't take O(n ^ 2)
in memory, just O(n)
. Maybe a bit more "optimal".
(by Tom Lilletveit、user529758)