优化慢速嵌套循环

时间:2015-07-10 17:20:03

标签: ios arrays swift

我的循环运行缓慢。是否有一种更有效的方法可以在swift中相互检查两个数组。

for photo in foodPhotos {
    for restaurant in self.restaurants {
        if (restaurant.objectId == photo.objectId){
            self.detailsForFoodPhotos.append(restaurant) // create array of ordered restaurants
            break // break if we find the matching restaurant
        }
    }
}

解释

对于每个元素,循环在第一个数组(objectId)中找到foodPhotos,其匹配第二个数组(objectId)中元素的restaurants

如果objectIds匹配,请将restaurants元素保存在detailsForFoodPhotos中。继续,直到检查完所有foodPhotos

实施例

照片数组:foodPhotos

[ photo1, photo2, photo3 ]

餐厅数组restaurants

[ restaurant1, restaurant2, restaurant3, restaurant4, restaurant3 ]

循环检查哪些photo.objectID匹配restaurant.objectID。然后使用匹配的餐馆创建一个新数组。

输出数组:detailsForFoodPhotos

[ restaurant3, restaurant1, restaurant2 ] 
// photo1.objectID == restaurant3.objectID
// photo2.objectID == restaurant1.objectID
// photo3.objectID == restaurant2.objectID

2 个答案:

答案 0 :(得分:1)

我仍然认为我的另一个答案是要走的路。但是,你还没有接受它,并且你已经提供了一些实际的数据输入和所需的输出,所以这里是一个产生它的解决方案:

struct Photo {
    let objectID : Int
}
struct Restaurant {
    let objectID : Int
}

let foodPhotos = [Photo(objectID:1), Photo(objectID:2), Photo(objectID:3)]
let restaurants = [Restaurant(objectID:3), Restaurant(objectID:1), Restaurant(objectID:2)]
var d = [Int:Int]()
for (ix,r) in restaurants.enumerate() {
    d[r.objectID] = ix
}
var detailsForFoodPhotos = [Restaurant]()
for p in foodPhotos {
    if let ix = d[p.objectID] {
        detailsForFoodPhotos.append(restaurants[ix])
    }
}
// Now I'll prove that it worked
print(foodPhotos)
// [Photo(objectID: 1), Photo(objectID: 2), Photo(objectID: 3)]
print(restaurants)
// [Restaurant(objectID: 3), Restaurant(objectID: 1), Restaurant(objectID: 2)]
print(detailsForFoodPhotos)
// [Restaurant(objectID: 1), Restaurant(objectID: 2), Restaurant(objectID: 3)]

这只需要两个简单的循环;两者都非常快。解决方案的关键是生成一个中间查找表(字典),d,在objectID上散列以索引到第二个数组。

答案 1 :(得分:-2)

您可以使用字典删除内部循环。只需在字典中使用element.objectId进行索引。如果它是零,则不存在,否则它存在。如果你需要我可以提供的代码。