From ab934e8ebcdbc8a4eac1e7d41c444d8f78f042c7 Mon Sep 17 00:00:00 2001 From: tid Date: Tue, 10 Nov 2020 16:27:51 +0900 Subject: [PATCH] Improved css conversion performance --- Sources/Kanna/CSS.swift | 6 +++++- Tests/KannaTests/KannaCSSTests.swift | 16 ++++++++++------ 2 files changed, 15 insertions(+), 7 deletions(-) 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) + } + } } }