diff --git a/Sources/Kanna/CSS.swift b/Sources/Kanna/CSS.swift index 7fc5c81..9f7e9f8 100755 --- a/Sources/Kanna/CSS.swift +++ b/Sources/Kanna/CSS.swift @@ -103,10 +103,14 @@ public enum CSS { } } +private var regexDict: [String: AKRegularExpression] = [:] private func firstMatch(_ pattern: String) -> (String) -> AKTextCheckingResult? { return { str in let length = str.utf16.count - guard let regex = try? AKRegularExpression(pattern: pattern, options: .caseInsensitive) else { + if regexDict[pattern] == nil { + regexDict[pattern] = try? AKRegularExpression(pattern: pattern, options: .caseInsensitive) + } + guard let regex = regexDict[pattern] else { return nil } if let result = regex.firstMatch(in: str, options: .reportProgress, range: NSRange(location: 0, length: length)) { diff --git a/Tests/KannaTests/KannaCSSTests.swift b/Tests/KannaTests/KannaCSSTests.swift index 01c6e9a..1e11893 100644 --- a/Tests/KannaTests/KannaCSSTests.swift +++ b/Tests/KannaTests/KannaCSSTests.swift @@ -93,12 +93,16 @@ class KannaCSSTests: XCTestCase { ] func testCSStoXPath() { - for testCase in css2xpath { - do { - let xpath = try CSS.toXPath(testCase.css) - XCTAssert(xpath == testCase.xpath, "Create XPath = [\(xpath)] != [\(testCase.xpath)]") - } catch { - XCTAssert(false, error.localizedDescription) + self.measure { + (0..<100).forEach { _ in + for testCase in css2xpath { + do { + let xpath = try CSS.toXPath(testCase.css) + XCTAssert(xpath == testCase.xpath, "Create XPath = [\(xpath)] != [\(testCase.xpath)]") + } catch { + XCTAssert(false, error.localizedDescription) + } + } } }