0

I have an iPhone application that needs to sort a couple of NSMutableArrays, this arrays contain around 3000 elements.

The idea is to sort them once when the application starts, then every iteration I need to insert 9 elements to each of those arrays. Is there an efficient way with NSMutableArrays, to insert those 9 elements in a sorted way?

I don't know if sortUsingSelector: is "smart" enough to take advantage of the array being mostly sorted and only 9 elements being "unsorted".

Thanks!

1

3 Answers 3

4

I've have good success with just tossing elements into the array and then sorting it with the NSArray sorting methods.

It sounds inefficient but these Foundation classes aren't just lightweight wrappers around standard C arrays . Instead, they have a tremendous amount of code all built to make these standard task easy and quick.

A good rule of thumb is to use the quickest and easiest method provided by the built-in classes and then investigate a different methods only when you've proven the easy method isn't fast enough.

Premature optimization is the root of all evil.

Sign up to request clarification or add additional context in comments.

Comments

2

Best way to sort NSMutableArray? Use sortUsingSelector message. It should be smart enough.

To insert the elements in a sorted way you can previously do a binary search on the array, and then insert the element in the desired position.

Having answered your question, I would suggest you to consider using SQLite to store the elements you want for the array. That way, your problem will reduce to querying the table with the elements with an order by clause, and inserting the new 9 elements with insert sentence. If you have an index on the order you are looking for, it should be fast.

1 Comment

-1 It's not smart enough. The documentation alludes to this in the description of sortedArrayUsingFunction:context:hint:.
1

I was looking for some actual measurements comparing the different sorts and didn't find any. So I measured it myself for an actual data set that I'm working with. Here are the results for my data, YMMV. Times in seconds.

2011-12-26 14:09:36.264 sorting 302 objects
2011-12-26 14:09:36.335 sorted w/descriptors in  0.051
2011-12-26 14:09:36.361 sorted w/selector    in  0.004
2011-12-26 14:09:36.394 sorted w/function    in  0.010
2011-12-26 14:09:36.427 sorted w/comparator  in  0.011

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.