Skip to content

Commit

Permalink
Merge pull request #244 from tid-kijyun/fix/improved_css_conversion_p…
Browse files Browse the repository at this point in the history
…erformance

Improved css conversion performance
  • Loading branch information
tid-kijyun authored Nov 10, 2020
2 parents 4a80ebe + ab934e8 commit 9760f64
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
6 changes: 5 additions & 1 deletion Sources/Kanna/CSS.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down
16 changes: 10 additions & 6 deletions Tests/KannaTests/KannaCSSTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}
}

Expand Down

0 comments on commit 9760f64

Please sign in to comment.