简体   繁体   中英

Best way to loop through an array as fast as possible?

Right now, my app retrieves around 1000 CKRecords which gets put into an array. I need to loop through this array later on. When I just had about 100 records to loop through my app worked smoothly and fast, but now it gets slower and slower as the number of records grow. I plan to have around 3000 CKRecords to retrieve so this could be a serious problem for me.

This is what I have come up with for now:

//movies == The NSMutableArray
if let recordMovies = movies.objectEnumerator().allObjects as? [CKRecord] {
        for movie in recordMovies {
       //Looping
       print(movie.objectForKey("Title") as? String)
       {
    }

But this doesn´t help a lot, seeing as I have to turn the NSMutableArray into an Array of CKRecords. I do this because I have to access the CKRecords attributes when looping, such as movieTitle. What measures can I take to speed up the looping process

Iterating through 1000 (or 5000) elements of an array should take a tiny fraction of a second.

Printing to the debug console is very slow however. Get rid if your print statement.

If movies is an array of CKRecord objects, why can't you just cast it to the desired array type?

let start = NSDate.timeIntervalSinceReferenceDate()
if let recordMovies = movies as? [CKRecord] {
  for movie in recordMovies {
    //Do whatever work you need to do on each object, but DON'T use print
  {
}
let elapsed = NSDate.timeIntervalSinceReferenceDate() - start
print( "iterating through the loop took \(elapsed) seconds")

You can save a lot of time by making "movies" not just an NSMutableArray, but an NSMutableArray of CKRecords, which makes it unnecessary to convert the array from NSMutableArray to a Swift array of CKRecord.

In Objective-C: Instead of

NSMutableArray* movies;

you use

NSMutableArray <CKRecord*> *movies;

As a result, movies [1] for example will have type CKRecord*, not id. An assignment movies [1] = something; requires that "something" is of type CKRecord* or id, nothing else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM