Search code examples
iosobjective-crecursionobjective-c-category

Reverse NSString recursively in category


I made this category for reversing an NSString in a recursive way. I'm getting the correct answer. But I'm not sure if this is okay with memory management. I don't know much about memory management in Objective-C.

Any other efficient way would be highly admirable.

-(NSString *)reverseString{
    if ([self length]<2) {
        return self;
    } else {
        return [[[self substringFromIndex:1] reverseString] stringByAppendingString:[self substringToIndex:1]];
    }
}

However, this question is similar to Reverse NSString text but not the duplicate because here I'm implementing it with recursion. And I specifically asked about the memory consumption not for any code example.


Solution

  • Using recursion to reverse a string is an interesting thought exercise, but it is goning to be very slow and a dreadful wasteful of memory. You need to create 2n temporary strings. (where n is the number of characters in your string) n of those strings are only 1 character long, and the other n strings are 1, 2, 3, 4, 5, Etc. Characters, up to n-1.

    (Memory allocation is very slow.)

    Plus you create n stack frames. As rmaddy says in his comment, you'll likely cause a stack overflow for very long strings.

    If you are doing this to learn about recursion, fine. Otherwise, toss this approach completely and write code that loops through the array backwards, appending each character to a mutable string.