Let's Build NSMutableArray
mikeash.com
mikeash.com
In the interest of brevity and simplicity, and at the cost of correctness and reliability - I understand the intent, but I believe that there is a balance to be struck on this for all code, whether example, prototype, or production.
Because sample code so very often chooses an extreme of that spectrum, it is easy for neophyte coders to end up thinking that is how all code should be written.
* a first version illustrating the core concepts
* a second more complex version aimed at showing proper coding practices including comments showing where you can have performance or security issues.
It would be a nice addition to the many source code beautifiers/formatters out there.
It's worth pointing out that the performance hit of memmove vs. memcpy is a single check in memmove which decides, based on if the source or destination address is higher, whether to copy front to back or back to front. You're never going to win any measurable performance gains by replacing a memmove call with a memcpy.
My only nitpick is ignoring the capacity variable in initWithCapacity. Really, a simple allocation of memory here and setting the _capacity variable is all that's needed. It IS an important implementation to write - especially if you know you're going to be working with a large array size right from the get go to avoid the memory copies.
But otherwise - I enjoyed that. I think I may just start following his blog to refresh my knowledge with other data structures!
This NSMutableArray subclass has O(1) access, as one expects from an array. NSMutableArray itself, however, only guarantees O(log n).
I'm nearly positive that the wording used to be much more vague on that point, as I remember thinking in my early days that it was so fuzzy as to be nearly pointless to go out of your way to give an accurate capacity. Mike is an old-time Cocoa guy, so if my memory is serving me well, he was probably thinking of the same old wording.