簡體   English   中英

使用謂詞進行過濾需要花費大量時間

[英]Filter using a predicate takes a lot of time

我在數組中有40k字符串。 我想過濾數組,以便僅獲取匹配的字符串。 我有一些先決條件,例如它之間可以有分隔符,應該是單詞搜索,搜索可以有多個單詞。 因此,我使用了正則表達式,這需要很多時間。

以下是我僅出於表示目的而生成的代碼。

var arr = [String]()
for index in stride(from: 0, to: 40000, by: 1) {
    arr.append("Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda.")
}

// We specify the words to be searched here
let searchTexts = ["aliqua", "Ut"]

// The time the execution started
print(Date().timeIntervalSince1970)


let predicate = NSPredicate(format: "SELF matches[cd] %@", ".*\\b\(searchTexts.joined(separator: "[ ,.!?;:\"(')-]*"))\\b.*")
let fil = arr.filter { (str) -> Bool in
    return predicate.evaluate(with: str)
}

// The time the execution stopped
print(Date().timeIntervalSince1970)

在iOS模擬器中需要2秒。 它需要更多的設備。

如何改善正則表達式? 我搜索了很多網站,但並沒有幫助我。

編輯:

由於涉及核心數據,因此上述問題已被修改。

我現在的實際問題是我們如何將相同的邏輯應用於核心數據提取?

如果只需要部分匹配,請不要使用需要整個字符串匹配的方法。 帶有MATCHES NSPredicate需要完整的字符串匹配,並且您必須使用.*或類似的字符串來確保。 但是, .*貪婪點圖案會占據整行,然后回溯以容納后續圖案的文本。 .*之后的模式越多,模式的效率就越低。

您需要使用一種允許部分匹配的方法,從而使您擺脫.* ,例如range(of:options:range:locale:)在傳遞.regularExpression選項的同時,指定一個range(of:options:range:locale:)

在上述情況下,您可以刪除let predicate = NSPredicate(format: "SELF matches[cd] %@", ".*\\\\b\\(searchTexts.joined(separator: "[ ,.!?;:\\"(')-]*"))\\\\b.*"然后將return predicate.evaluate(with: str)替換為

return str.range(of: "\\b\(searchTexts.joined(separator: "[ ,.!?;:\"(')-]*"))\\b", options: .regularExpression) != nil

請參閱新的正則表達式演示 (56個步驟)和正則表達式演示 (541個步驟)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM