From d2e7210809551f0fc0c862bbc35154b07f0addc6 Mon Sep 17 00:00:00 2001 From: Jeffrey Macko Date: Fri, 13 Nov 2026 23:56:41 +0100 Subject: [PATCH 1/9] Add benchmarks on package-benchmark Benchmarks/ is a separate package, as in swift-arazzo, so the library never depends on package-benchmark or Foundation. 25 benchmarks: JSON parsing and printing, path parsing in both Dialects, queries on a generated 1.4 MB store and on the compliance suite, JSON Pointer, mutations and Codable. Tools: p50 compares two markdown runs, and scripts/profile.sh runs Time Profiler on one benchmark and prints its hottest functions. --- .gitignore | 3 + .../JSONPathBenchmarks.swift | 160 ++++++++++++++++++ Benchmarks/Package.swift | 31 ++++ Benchmarks/Tools/Hotspots/main.swift | 86 ++++++++++ Benchmarks/Tools/P50/main.swift | 54 ++++++ Benchmarks/scripts/profile.sh | 23 +++ 6 files changed, 357 insertions(+) create mode 100644 Benchmarks/Benchmarks/JSONPathBenchmarks/JSONPathBenchmarks.swift create mode 100644 Benchmarks/Package.swift create mode 100644 Benchmarks/Tools/Hotspots/main.swift create mode 100644 Benchmarks/Tools/P50/main.swift create mode 100755 Benchmarks/scripts/profile.sh diff --git a/.gitignore b/.gitignore index c377b7b..a94633d 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,6 @@ xcuserdata/ DerivedData/ *.xcodeproj Package.resolved +/Benchmarks/.build +/Benchmarks/.swiftpm +/Benchmarks/.benchmarkBaselines diff --git a/Benchmarks/Benchmarks/JSONPathBenchmarks/JSONPathBenchmarks.swift b/Benchmarks/Benchmarks/JSONPathBenchmarks/JSONPathBenchmarks.swift new file mode 100644 index 0000000..30c7c13 --- /dev/null +++ b/Benchmarks/Benchmarks/JSONPathBenchmarks/JSONPathBenchmarks.swift @@ -0,0 +1,160 @@ +import Benchmark +import Foundation +import JSONPath + +/// The documents the benchmarks read: the compliance test suite the tests run, and a generated store far larger than +/// the README's, to show costs that grow with size. +enum Fixtures { + /// `Tests/JSONPathTests/Fixtures/cts.json`, 232 KB of real-world JSON: long strings, deep nesting, escapes. + static let ctsText: String = { + let url = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + .deletingLastPathComponent().appendingPathComponent("Tests/JSONPathTests/Fixtures/cts.json") + return try! String(contentsOf: url, encoding: .utf8) + }() + + static let cts: JSONValue = try! JSONValue(parsing: ctsText) + + /// The README's bookstore with `books` books, each with nested reviews: about 1.4 MB of JSON for 5,000 books. + static func storeText(books: Int = 5_000) -> String { + let categories = ["reference", "fiction", "poetry", "history"] + let items = (0.. 3]) > 1]", "$..*", +] +let jaywayExpressions = [ + "$.store.book[0].title", "$['store']['book'][*]['author']", "$..author", "$.store.book[-2:]", + "$..book[?(@.price < 10 && @.category == 'fiction')].title", "$..book[?(@.isbn =~ /0-1.*/)]", + "$.store.book[?(@.reviews.length() > 1)]", "$..book.length()", +] + +/// A Codable model of one book. +struct Book: Codable { + struct Review: Codable { + var stars: Int + var by: String + var tags: [String?]? + } + var category: String + var author: String + var title: String + var isbn: String + var price: Double + var available: Bool + var reviews: [Review] +} + +let benchmarks: @Sendable () -> Void = { + Benchmark.defaultConfiguration = .init( + metrics: [.wallClock, .cpuTotal, .mallocCountTotal, .peakMemoryResident, .retainCount], + // Exact counts and microseconds, so a change of a few percent shows up in a comparison. + timeUnits: .microseconds, + units: [.mallocCountTotal: .count, .retainCount: .count], + maxDuration: .seconds(2), + maxIterations: 1_000 + ) + + // MARK: JSON text + + Benchmark("Parse JSON, compliance suite") { _ in + blackHole(try JSONValue(parsing: Fixtures.ctsText)) + } + Benchmark("Parse JSON, large") { _ in + blackHole(try JSONValue(parsing: Fixtures.largeText)) + } + Benchmark("Parse JSON from bytes, large") { benchmark in + let bytes = Array(Fixtures.largeText.utf8) + benchmark.startMeasurement() + blackHole(try JSONValue(parsing: bytes)) + } + Benchmark("Print JSON, large") { _ in + blackHole(Fixtures.large.jsonString) + } + Benchmark("Print JSON pretty and sorted, large") { _ in + blackHole(Fixtures.large.jsonString(prettyPrinted: true, sortedKeys: true)) + } + + // MARK: Parsing paths + + Benchmark("Parse paths, RFC 9535") { _ in + for expression in rfcExpressions { blackHole(try JSONPath(expression)) } + } + Benchmark("Parse paths, Jayway") { _ in + for expression in jaywayExpressions { blackHole(try JSONPath(expression, dialect: .jayway)) } + } + + // MARK: Queries + + for (dialect, expressions) in [(JSONPath.Dialect.rfc9535, rfcExpressions), (.jayway, jaywayExpressions)] { + let name = dialect == .rfc9535 ? "RFC 9535" : "Jayway" + let paths = expressions.map { try! JSONPath($0, dialect: dialect) } + Benchmark("Query \(name), every expression, large") { _ in + for path in paths { blackHole(try path.values(in: Fixtures.large)) } + } + Benchmark("Query \(name), descendants, large") { _ in + blackHole(try paths[2].values(in: Fixtures.large)) + } + Benchmark("Query \(name), filter, large") { _ in + blackHole(try paths[4].values(in: Fixtures.large)) + } + Benchmark("Query \(name), nodes with normalized paths, large") { _ in + blackHole(try paths[1].nodes(in: Fixtures.large)) + } + } + let everything = try! JSONPath("$..*") + Benchmark("Query RFC 9535, every node, compliance suite") { _ in + blackHole(try everything.values(in: Fixtures.cts)) + } + + // MARK: Pointers and mutation + + let pointers = (0..<1_000).map { try! JSONPointer("/store/book/\($0 * 5)/reviews/1/by") } + Benchmark("Resolve JSON pointers, large") { _ in + for pointer in pointers { blackHole(pointer.resolve(in: Fixtures.large)) } + } + let prices = try! JSONPath("$..price") + Benchmark("Replace every price, large") { benchmark in + var document = Fixtures.large + benchmark.startMeasurement() + blackHole(try document.replace(prices, with: 1)) + blackHole(document) + } + let unavailable = try! JSONPath("$.store.book[?@.available == false]") + Benchmark("Remove filtered books, large") { benchmark in + var document = Fixtures.large + benchmark.startMeasurement() + blackHole(try document.remove(unavailable)) + blackHole(document) + } + + // MARK: Codable + + let books = try! JSONPath("$.store.book[*]").values(in: Fixtures.large) + Benchmark("Decode books, large") { _ in + blackHole(try JSONValueDecoder().decode(Book.self, from: books)) + } + let decoded = try! JSONValueDecoder().decode(Book.self, from: books) + Benchmark("Encode books, large") { _ in + blackHole(try JSONValueEncoder().encode(decoded)) + } +} diff --git a/Benchmarks/Package.swift b/Benchmarks/Package.swift new file mode 100644 index 0000000..b1553ae --- /dev/null +++ b/Benchmarks/Package.swift @@ -0,0 +1,31 @@ +// swift-tools-version: 6.1 +import PackageDescription + +// swift-jsonpath's benchmarks, on ordo-one/package-benchmark (https://www.swift.org/blog/benchmarks/). A separate +// package so the benchmark dependency and Foundation stay out of the library's dependency budget. Run from the +// repository root: `swift package --package-path Benchmarks benchmark`. +let package = Package( + name: "Benchmarks", + platforms: [.macOS(.v15)], + dependencies: [ + .package(name: "swift-jsonpath", path: ".."), + .package(url: "https://github.com/ordo-one/package-benchmark.git", from: "1.38.0"), + ], + targets: [ + .executableTarget( + name: "JSONPathBenchmarks", + dependencies: [ + .product(name: "Benchmark", package: "package-benchmark"), + .product(name: "JSONPath", package: "swift-jsonpath"), + ], + path: "Benchmarks/JSONPathBenchmarks", + plugins: [ + .plugin(name: "BenchmarkPlugin", package: "package-benchmark") + ] + ), + // Reads two `benchmark --format markdown` outputs and prints each benchmark's p50 before and after. + .executableTarget(name: "p50", path: "Tools/P50"), + // Reads an exported Time Profiler table and prints the hottest functions (scripts/profile.sh). + .executableTarget(name: "hotspots", path: "Tools/Hotspots"), + ] +) diff --git a/Benchmarks/Tools/Hotspots/main.swift b/Benchmarks/Tools/Hotspots/main.swift new file mode 100644 index 0000000..0e3dd0f --- /dev/null +++ b/Benchmarks/Tools/Hotspots/main.swift @@ -0,0 +1,86 @@ +import Foundation + +// Usage: swift run --package-path Benchmarks hotspots profile.xml [count] +// profile.xml is `xcrun xctrace export --xpath '…/table[@schema="time-profile"]'` (scripts/profile.sh writes it). +// Prints the functions with the most samples of their own (self) and the library functions with the most samples +// under them (inclusive). package-benchmark's ARC counting hooks are left out: they exist only while measuring. + +/// Reads the rows of an exported time-profile table. Frames and backtraces are written once and then referenced +/// by id, so both are remembered. +final class ProfileReader: NSObject, XMLParserDelegate { + var frameNames: [String: String] = [:] + var backtraces: [String: [String]] = [:] + var samples: [[String]] = [] + private var current: [String]? + private var currentID: String? + + func parser( + _ parser: XMLParser, didStartElement element: String, namespaceURI: String?, qualifiedName: String?, + attributes: [String: String] = [:] + ) { + switch element { + case "tagged-backtrace", "backtrace": + if let ref = attributes["ref"] { + samples.append(backtraces[ref] ?? []) + } else { + current = [] + currentID = attributes["id"] + } + case "frame" where current != nil: + if let ref = attributes["ref"] { + current?.append(frameNames[ref] ?? "?") + } else { + let name = attributes["name"] ?? "?" + if let id = attributes["id"] { frameNames[id] = name } + current?.append(name) + } + default: + break + } + } + + func parser(_ parser: XMLParser, didEndElement element: String, namespaceURI: String?, qualifiedName: String?) { + guard element == "tagged-backtrace" || element == "backtrace", let frames = current else { return } + if let currentID { backtraces[currentID] = frames } + samples.append(frames) + current = nil + currentID = nil + } +} + +let arguments = CommandLine.arguments +guard arguments.count >= 2, let parser = XMLParser(contentsOf: URL(fileURLWithPath: arguments[1])) else { + print("usage: hotspots [count]") + exit(2) +} +let count = arguments.count > 2 ? Int(arguments[2]) ?? 20 : 20 +let reader = ProfileReader() +parser.delegate = reader +guard parser.parse() else { + print("could not read \(arguments[1]): \(parser.parserError.map { "\($0)" } ?? "unknown error")") + exit(1) +} + +let measuring = /ARCStatsProducer|_swift_(retain|release)_(adapter|hook)|MallocInterposer/ +func short(_ name: String) -> String { String(name.prefix { $0 != "(" }.suffix(110)) } + +var selfSamples: [String: Int] = [:] +var inclusiveSamples: [String: Int] = [:] +var total = 0 +for frames in reader.samples where !frames.isEmpty { + guard !frames.contains(where: { $0.contains(measuring) }) else { continue } + total += 1 + selfSamples[short(frames[0]), default: 0] += 1 + for name in Set(frames.map(short)) where name.contains(/JSONPath/) { + inclusiveSamples[name, default: 0] += 1 + } +} +func report(_ title: String, _ counts: [String: Int], of total: Int) { + print(title) + for (name, samples) in counts.sorted(by: { $0.value > $1.value }).prefix(count) { + print(String(format: "%5.1f%% ", 100 * Double(samples) / Double(max(total, 1))) + name) + } +} +print("\(total) samples") +report("Self", selfSamples, of: total) +report("Inclusive (JSONPath)", inclusiveSamples, of: total) diff --git a/Benchmarks/Tools/P50/main.swift b/Benchmarks/Tools/P50/main.swift new file mode 100644 index 0000000..7e89788 --- /dev/null +++ b/Benchmarks/Tools/P50/main.swift @@ -0,0 +1,54 @@ +import Foundation + +// Usage: swift run --package-path Benchmarks p50 before.md after.md +// Each file is the output of `swift package --package-path Benchmarks benchmark --format markdown --no-progress`. + +/// A benchmark's p50 wall clock in microseconds and p50 malloc count. +struct Medians { + var wallClock: Double? + var mallocs: Double? +} + +func medians(inFile path: String) throws -> [(name: String, medians: Medians)] { + let text = try String(contentsOfFile: path, encoding: .utf8) + // A row: | Time (wall clock) (μs) * | p0 | p25 | p50 | … The unit is absent for plain counts. + let row = + /^\|\s*(Malloc \(total\)|Time \(wall clock\))\s*(?:\(([^)]*)\))?\s*\*?\s*\|\s*[\d,]+\s*\|\s*[\d,]+\s*\|\s*([\d,]+)/ + let scale: [String: Double] = ["ns": 1e-3, "μs": 1, "us": 1, "ms": 1e3, "s": 1e6, "K": 1e3, "M": 1e6] + var result: [(name: String, medians: Medians)] = [] + for line in text.split(separator: "\n") { + if line.hasPrefix("### ") { + let name = line.dropFirst(4).replacingOccurrences(of: " metrics", with: "") + result.append((name, Medians())) + } else if let match = line.firstMatch(of: row), !result.isEmpty { + let value = + Double(match.3.replacingOccurrences(of: ",", with: ""))! * (match.2.map { scale[String($0)] ?? 1 } ?? 1) + if match.1 == "Malloc (total)" { + result[result.count - 1].medians.mallocs = result[result.count - 1].medians.mallocs ?? value + } else { + result[result.count - 1].medians.wallClock = result[result.count - 1].medians.wallClock ?? value + } + } + } + return result +} + +let arguments = CommandLine.arguments +guard arguments.count == 3 else { + print("usage: p50 ") + exit(2) +} +let before = Dictionary( + try medians(inFile: arguments[1]).map { ($0.name, $0.medians) }, uniquingKeysWith: { a, _ in a }) +func cell(_ old: Double?, _ new: Double?, _ format: String) -> String { + guard let new else { return "" } + guard let old else { return String(format: format, new) } + return String(format: "\(format) → \(format) (%.2fx)", old, new, new / old) +} +print("| Benchmark | Wall clock p50 (µs) | Mallocs p50 |") +print("|---|---|---|") +for (name, after) in try medians(inFile: arguments[2]) { + let old = before[name] + print( + "| \(name) | \(cell(old?.wallClock, after.wallClock, "%.1f")) | \(cell(old?.mallocs, after.mallocs, "%.0f")) |") +} diff --git a/Benchmarks/scripts/profile.sh b/Benchmarks/scripts/profile.sh new file mode 100755 index 0000000..78d81f2 --- /dev/null +++ b/Benchmarks/scripts/profile.sh @@ -0,0 +1,23 @@ +#!/bin/sh +# Profiles one benchmark with Instruments' Time Profiler and prints its hottest functions. +# Usage, from the repository root: Benchmarks/scripts/profile.sh 'Query RFC 9535, descendants, large' [count] +# The name is the benchmark's, matched exactly. The trace is kept in Benchmarks/.build/profiles to open in Instruments. +set -eu + +name=$1 +count=${2:-20} +package=$(cd "$(dirname "$0")/.." && pwd) +swift build --package-path "$package" -c release --product JSONPathBenchmarks +swift build --package-path "$package" -c release --product hotspots +bin=$(swift build --package-path "$package" -c release --show-bin-path) + +out="$package/.build/profiles" +mkdir -p "$out" +trace="$out/$(echo "$name" | tr -c 'A-Za-z0-9' '-').trace" +rm -rf "$trace" +# Instruments symbolicates only a binary launched by its absolute path. +xcrun xctrace record --quiet --template 'Time Profiler' --output "$trace" --launch -- \ + "$bin/JSONPathBenchmarks" --filter "^$name\$" +xcrun xctrace export --input "$trace" \ + --xpath '/trace-toc/run[@number="1"]/data/table[@schema="time-profile"]' > "$trace.xml" +"$bin/hotspots" "$trace.xml" "$count" From f5d4dcf236aef49c398259a33b8cfceb42ac8470 Mon Sep 17 00:00:00 2001 From: Jeffrey Macko Date: Fri, 13 Nov 2026 23:56:41 +0100 Subject: [PATCH 2/9] Mutate in place: replace and remove no longer copy their containers update(_:_:_:) bound each container while the value still held it, so copy-on-write copied the whole container on every write: replacing all 5,000 prices copied the 5,000-book array 5,000 times. Each container is now moved out before it changes and put back after, also on a throw. Replace every price, large: 412 ms -> 12.3 ms (34x) Remove filtered books, large: 112 ms -> 2.6 ms (43x) A test pins value semantics: mutating a copy leaves the original as is. --- Sources/JSONPath/Mutation.swift | 49 ++++++++++++++-------- Sources/JSONPath/OrderedDictionary.swift | 7 ++++ Tests/JSONPathTests/JSONPathAPITests.swift | 21 ++++++++++ 3 files changed, 59 insertions(+), 18 deletions(-) diff --git a/Sources/JSONPath/Mutation.swift b/Sources/JSONPath/Mutation.swift index 524fb5d..4b42e5b 100644 --- a/Sources/JSONPath/Mutation.swift +++ b/Sources/JSONPath/Mutation.swift @@ -63,15 +63,18 @@ extension JSONValue { return } try? Self.update(&self, parent.elements[...]) { container in - switch (container, last) { - case (.object(var object)?, .name(let name)): + // The container is moved out before it changes, as in `update`, so removing does not copy it. + switch last { + case .name(let name): + guard case .object(var object)? = container else { return } + container = nil object.removeValue(forKey: name) container = .object(object) - case (.array(var array)?, .index(let index)) where array.indices.contains(index): + case .index(let index): + guard case .array(var array)? = container, array.indices.contains(index) else { return } + container = nil array.remove(at: index) container = .array(array) - default: - break } } } @@ -119,28 +122,37 @@ extension JSONValue { ) throws { guard let first = elements.first else { var optional: JSONValue? = value + value = .null // so `body` gets the only reference and changes it in place body(&optional) value = optional ?? .null return } let rest = elements.dropFirst() - switch (value, first) { - case (.object(var object), .name(let name)): + // Each container is moved out of `value` before it changes, and put back after, even on a throw: while + // `value` still held it, the container would be shared and every change would copy it whole. The switch is + // on `first` alone, since a tuple of `(value, first)` would hold a second reference too. + switch first { + case .name(let name): + guard case .object(var object) = value else { throw cannotApply(first, to: value) } + value = .null + defer { value = .object(object) } if rest.isEmpty { var child = object[name] + if case .some = child { object[name] = .null } // keeps the member's position, drops the second reference body(&child) object[name] = child } else { - guard var child = object[name] else { - throw MutationError(message: "No member '\(name)'") - } - try update(&child, rest, body) - object[name] = child + let found = try object.modifyValue(forKey: name) { child in try update(&child, rest, body) } + guard found != nil else { throw MutationError(message: "No member '\(name)'") } } - value = .object(object) - case (.array(var array), .index(let index)): + case .index(let index): + guard case .array(var array) = value else { throw cannotApply(first, to: value) } + value = .null + defer { value = .array(array) } if rest.isEmpty { - var child: JSONValue? = array.indices.contains(index) ? array[index] : nil + // `.none`, not `nil`: in this ternary Swift reads `nil` as `JSONValue.null`. + var child: JSONValue? = array.indices.contains(index) ? .some(array[index]) : .none + if case .some = child { array[index] = .null } // drops the second reference body(&child) if let child { if array.indices.contains(index) { @@ -159,12 +171,13 @@ extension JSONValue { } try update(&array[index], rest, body) } - value = .array(array) - default: - throw MutationError(message: "Cannot apply \(first) to a \(value.typeName)") } } + static func cannotApply(_ element: NormalizedPath.Element, to value: JSONValue) -> MutationError { + MutationError(message: "Cannot apply \(element) to a \(value.typeName)") + } + /// The JSON type name: `object`, `array`, `string`, `number`, `boolean` or `null`. public var typeName: String { switch self { diff --git a/Sources/JSONPath/OrderedDictionary.swift b/Sources/JSONPath/OrderedDictionary.swift index 8249467..001936c 100644 --- a/Sources/JSONPath/OrderedDictionary.swift +++ b/Sources/JSONPath/OrderedDictionary.swift @@ -48,6 +48,13 @@ public struct OrderedDictionary { public func contains(key: Key) -> Bool { storage[key] != nil } + /// Calls `body` with the value for `key` in place, so a uniquely referenced value is not copied, or returns `nil` + /// when there is no such key. + mutating func modifyValue(forKey key: Key, _ body: (inout Value) throws -> R) rethrows -> R? { + guard let index = storage.index(forKey: key) else { return nil } + return try body(&storage.values[index]) + } + /// The stored key equal to `key` and its value. (Swift `String` equality is canonical-equivalence /// based; callers that need code-point equality compare the returned key.) func entry(forKey key: Key) -> (key: Key, value: Value)? { diff --git a/Tests/JSONPathTests/JSONPathAPITests.swift b/Tests/JSONPathTests/JSONPathAPITests.swift index 07c5ee5..a7149bd 100644 --- a/Tests/JSONPathTests/JSONPathAPITests.swift +++ b/Tests/JSONPathTests/JSONPathAPITests.swift @@ -201,6 +201,27 @@ struct MutationTests { #expect(value == [3, 4, 5]) } + @Test func mutationLeavesOtherCopiesUnchanged() throws { + // Given a document with nested arrays and objects, and a copy of it + let books: [JSONValue] = (0..<100).map { ["price": .integer($0), "tags": ["a", .integer($0)]] } + let original: JSONValue = ["store": ["book": .array(books)]] + var copy = original + + // When the copy is mutated at many locations, deep and shallow + let replaced = try copy.replace(JSONPath("$..price"), with: 0) + let removed = try copy.remove(JSONPath("$.store.book[?@.tags[1] >= 50]")) + try copy.set("x", at: JSONPointer("/store/book/0/tags/0")) + + // Then the copy has every change and the original none + #expect(replaced == 100) + #expect(removed == 50) + #expect(copy["store"]?["book"]?.arrayValue?.count == 50) + #expect(copy["store"]?["book"]?[49] == ["price": 0, "tags": ["a", 49]]) + #expect(copy["store"]?["book"]?[0]?["tags"] == ["x", 0]) + #expect(original == ["store": ["book": .array(books)]]) + #expect(original["store"]?["book"]?[99]?["price"] == 99) + } + @Test func normalizedPathSubscriptAndOrdering() throws { let value: JSONValue = ["a": [["b": 1]]] let path: NormalizedPath = ["a", 0, "b"] From 5ba2c18348bf6fc26ed1a226a165cc6319dae69a Mon Sep 17 00:00:00 2001 From: Jeffrey Macko Date: Fri, 13 Nov 2026 23:59:45 +0100 Subject: [PATCH 3/9] Build normalized paths only when the caller reads them Every visited node built its NormalizedPath (an array copy), including under values(in:), firstValue(in:), matches(_:) and every filter and function subquery, which all discard it. The evaluators now start from a nil location unless nodes(in:) asks for locations, and nil propagates. Query RFC 9535, descendants, large: 9.9 ms -> 2.1 ms, 95 K -> 15 mallocs Query Jayway, descendants, large: 4.2 ms -> 1.8 ms, 30 K -> 14 mallocs Query RFC 9535, filter, large: 11.1 ms -> 3.1 ms Query RFC 9535, every node, compliance suite: 2.0 ms -> 0.45 ms Query RFC 9535, every expression, large: 117 ms -> 74 ms nodes(in:) with normalized paths: unchanged --- Sources/JSONPath/JSONPath.swift | 18 +++++++++++------- Sources/JSONPath/JaywayEvaluator.swift | 8 ++++++-- Sources/JSONPath/RFC9535Evaluator.swift | 6 ++++-- 3 files changed, 21 insertions(+), 11 deletions(-) diff --git a/Sources/JSONPath/JSONPath.swift b/Sources/JSONPath/JSONPath.swift index f7a82de..ca70a02 100644 --- a/Sources/JSONPath/JSONPath.swift +++ b/Sources/JSONPath/JSONPath.swift @@ -94,15 +94,19 @@ public struct JSONPath: Hashable, Sendable, CustomStringConvertible { /// The nodes selected from `root`, in result order. public func nodes(in root: JSONValue) throws -> [Node] { - switch dialect { - case .rfc9535: try RFC9535Evaluator(root: root).evaluate(query, current: root) - case .jayway: try JaywayEvaluator(root: root).evaluate(query, current: root) - } + try evaluate(in: root, tracksLocations: true) } /// The values selected from `root`. public func values(in root: JSONValue) throws -> [JSONValue] { - try nodes(in: root).map(\.value) + try evaluate(in: root, tracksLocations: false).map(\.value) + } + + func evaluate(in root: JSONValue, tracksLocations: Bool) throws -> [Node] { + switch dialect { + case .rfc9535: try RFC9535Evaluator(root: root).evaluate(query, current: root, tracksLocations: tracksLocations) + case .jayway: try JaywayEvaluator(root: root).evaluate(query, current: root, tracksLocations: tracksLocations) + } } /// The normalized paths of the selected nodes (function results have none). @@ -112,12 +116,12 @@ public struct JSONPath: Hashable, Sendable, CustomStringConvertible { /// The first selected value, or `nil` when nothing matches. public func firstValue(in root: JSONValue) throws -> JSONValue? { - try nodes(in: root).first?.value + try values(in: root).first } /// `true` when at least one node is selected. public func matches(_ root: JSONValue) throws -> Bool { - try !nodes(in: root).isEmpty + try !values(in: root).isEmpty } /// Paths are equal when they have the same dialect and the same normalized form, diff --git a/Sources/JSONPath/JaywayEvaluator.swift b/Sources/JSONPath/JaywayEvaluator.swift index 37c5181..6c73e64 100644 --- a/Sources/JSONPath/JaywayEvaluator.swift +++ b/Sources/JSONPath/JaywayEvaluator.swift @@ -11,10 +11,14 @@ struct JaywayEvaluator { typealias Node = JSONPath.Node - func evaluate(_ query: JSONPath.Query, current: JSONValue) throws -> [Node] { + /// The selected nodes. Without `tracksLocations` every location is `nil`: building them costs an allocation per + /// visited node, and filters, functions and ``JSONPath/values(in:)`` read values only. + func evaluate(_ query: JSONPath.Query, current: JSONValue, tracksLocations: Bool = false) throws -> [Node] { let start = query.root == .root ? root : current var results: [Node] = [] - try run(query.segments[...], value: start, location: .root, upstreamDefinite: true) { results.append($0) } + try run(query.segments[...], value: start, location: tracksLocations ? .root : nil, upstreamDefinite: true) { + results.append($0) + } return results } diff --git a/Sources/JSONPath/RFC9535Evaluator.swift b/Sources/JSONPath/RFC9535Evaluator.swift index 9799843..fa623a9 100644 --- a/Sources/JSONPath/RFC9535Evaluator.swift +++ b/Sources/JSONPath/RFC9535Evaluator.swift @@ -4,8 +4,10 @@ struct RFC9535Evaluator { typealias Node = JSONPath.Node - func evaluate(_ query: JSONPath.Query, current: JSONValue) throws -> [Node] { - var nodes = [Node(location: .root, value: query.root == .root ? root : current)] + /// The selected nodes. Without `tracksLocations` every location is `nil`: building them costs an allocation per + /// visited node, and filters, functions and ``JSONPath/values(in:)`` read values only. + func evaluate(_ query: JSONPath.Query, current: JSONValue, tracksLocations: Bool = false) throws -> [Node] { + var nodes = [Node(location: tracksLocations ? .root : nil, value: query.root == .root ? root : current)] for segment in query.segments { var next: [Node] = [] switch segment { From 9e360d52e28100044ce8aa55b6ce0cd0f953bb6a Mon Sep 17 00:00:00 2001 From: Jeffrey Macko Date: Sat, 14 Nov 2026 00:01:42 +0100 Subject: [PATCH 4/9] Parse JSON strings and integers without building them scalar by scalar A string without escapes is decoded once from its bytes; with escapes, the unescaped UTF-8 is gathered in a buffer and decoded once, instead of appending each scalar to a String.UnicodeScalarView. Integers are read from the bytes with overflow checks instead of through a String; a fraction or exponent still goes through Double(String), which rounds correctly. Parse JSON, large (1.4 MB): 26.4 ms -> 9.1 ms, 310 K -> 115 K mallocs Parse JSON, compliance suite: 2.9 ms -> 1.0 ms, 34 K -> 13 K mallocs New tests: escapes next to multibyte text, escaped keys, invalid UTF-8 repaired to U+FFFD as before, Int.min and the first integer past it. --- Sources/JSONPath/JSONParser.swift | 61 ++++++++++++++-------- Tests/JSONPathTests/JSONPathAPITests.swift | 20 +++++++ 2 files changed, 59 insertions(+), 22 deletions(-) diff --git a/Sources/JSONPath/JSONParser.swift b/Sources/JSONPath/JSONParser.swift index 820f8c8..a0937c8 100644 --- a/Sources/JSONPath/JSONParser.swift +++ b/Sources/JSONPath/JSONParser.swift @@ -173,48 +173,65 @@ struct JSONTextParser { guard index < bytes.count, isDigit(bytes[index]) else { throw fail("invalid exponent") } while index < bytes.count, isDigit(bytes[index]) { index += 1 } } + if isInteger, let int = integer(start..) -> Int? { + let negative = bytes[range.lowerBound] == UInt8(ascii: "-") + var value = 0 + for index in (negative ? range.lowerBound + 1 : range.lowerBound).. Bool { byte >= UInt8(ascii: "0") && byte <= UInt8(ascii: "9") } + /// A string without escapes is decoded once from its bytes. With escapes, the unescaped UTF-8 is gathered in + /// a buffer and decoded once, rather than appended scalar by scalar. mutating func parseString() throws -> String { index += 1 // opening quote - var scalars = String.UnicodeScalarView() + var hasEscapes = false + var unescaped: [UInt8] = [] var runStart = index - func flushRun(_ end: Int, into scalars: inout String.UnicodeScalarView) { - if end > runStart { - scalars.append( - contentsOf: String(decoding: UnsafeBufferPointer(rebasing: bytes[runStart.. Date: Sat, 14 Nov 2026 00:04:44 +0100 Subject: [PATCH 5/9] Print JSON strings by runs instead of scalar by scalar Only ASCII bytes are escaped, so writeString copies the runs between them whole, multibyte UTF-8 included, instead of appending each scalar. The pretty printer writes keys and leaves into its output directly instead of building a jsonString for each. Print JSON, large: 15.3 ms -> 10.2 ms Print JSON pretty and sorted, large: 17.1 ms -> 16.4 ms (sorting keys dominates) New test: every escape next to multibyte text, compact and pretty. --- Sources/JSONPath/JSONValue.swift | 38 +++++++++++++--------- Sources/JSONPath/JSONValueCoding.swift | 5 +-- Tests/JSONPathTests/JSONPathAPITests.swift | 15 +++++++++ 3 files changed, 41 insertions(+), 17 deletions(-) diff --git a/Sources/JSONPath/JSONValue.swift b/Sources/JSONPath/JSONValue.swift index 85f34ad..e274212 100644 --- a/Sources/JSONPath/JSONValue.swift +++ b/Sources/JSONPath/JSONValue.swift @@ -165,7 +165,7 @@ extension JSONValue: CustomStringConvertible { return output } - private func write(to output: inout String) { + func write(to output: inout String) { switch self { case .null: output += "null" case .bool(let v): output += v ? "true" : "false" @@ -198,23 +198,31 @@ extension JSONValue: CustomStringConvertible { } } - private static func writeString(_ string: String, to output: inout String) { + /// Only ASCII bytes are ever escaped, so the runs between them, multibyte UTF-8 included, are copied whole. + static func writeString(_ string: String, to output: inout String) { output += "\"" - for scalar in string.unicodeScalars { - switch scalar { - case "\"": output += "\\\"" - case "\\": output += "\\\\" - case "\n": output += "\\n" - case "\r": output += "\\r" - case "\t": output += "\\t" - case "\u{08}": output += "\\b" - case "\u{0C}": output += "\\f" - case let s where s.value < 0x20: - let hex = String(s.value, radix: 16) - output += "\\u" + String(repeating: "0", count: 4 - hex.count) + hex - default: output.unicodeScalars.append(scalar) + let utf8 = string.utf8 + var runStart = utf8.startIndex + for (index, byte) in zip(utf8.indices, utf8) { + let escape: String + switch byte { + case UInt8(ascii: "\""): escape = "\\\"" + case UInt8(ascii: "\\"): escape = "\\\\" + case 0x0A: escape = "\\n" + case 0x0D: escape = "\\r" + case 0x09: escape = "\\t" + case 0x08: escape = "\\b" + case 0x0C: escape = "\\f" + case let byte where byte < 0x20: + let hex = String(byte, radix: 16) + escape = "\\u" + String(repeating: "0", count: 4 - hex.count) + hex + default: continue } + output += string[runStart.. 0 { output += "," } newline((indent ?? 0) + 1) - output += JSONValue.string(key).jsonString + (indent == nil ? ":" : ": ") + JSONValue.writeString(key, to: &output) + output += indent == nil ? ":" : ": " object[key]!.write(to: &output, indent: indent.map { $0 + 1 }, sortedKeys: sortedKeys) } newline(indent ?? 0) output += "}" default: - output += jsonString + write(to: &output) } } } diff --git a/Tests/JSONPathTests/JSONPathAPITests.swift b/Tests/JSONPathTests/JSONPathAPITests.swift index d28469a..da31f0a 100644 --- a/Tests/JSONPathTests/JSONPathAPITests.swift +++ b/Tests/JSONPathTests/JSONPathAPITests.swift @@ -31,6 +31,21 @@ struct JSONParserTests { #expect(repaired == "a\u{FFFD}\n\u{FFFD}") } + @Test func printsEscapesNextToMultibyteText() throws { + // Given strings with every escape next to multibyte text, as a key and as a value + let value: JSONValue = ["é\"k": "\u{01}日\\\u{1F}\t👍\u{08}\u{0C}\r"] + + // When printed compactly and pretty + let compact = value.jsonString + let pretty = value.jsonString(prettyPrinted: true) + + // Then only the ASCII escapes change, and both forms parse back to the value + #expect(compact == #"{"é\"k":"\u0001日\\\u001f\t👍\b\f\r"}"#) + #expect(pretty == "{\n " + #""é\"k": "\u0001日\\\u001f\t👍\b\f\r""# + "\n}") + #expect(try JSONValue(parsing: compact) == value) + #expect(try JSONValue(parsing: pretty) == value) + } + @Test func numbers() throws { #expect(try JSONValue(parsing: "0") == 0) #expect(try JSONValue(parsing: "-12") == -12) From c3bb8545fbb0c30055e789d4166bd9ff450c0644 Mon Sep 17 00:00:00 2001 From: Jeffrey Macko Date: Sat, 14 Nov 2026 00:10:26 +0100 Subject: [PATCH 6/9] OrderedDictionary: iterate without hashing, search small objects linearly The values lived in a Dictionary beside the ordered keys, so every iteration step and the values property hashed the key again. Keys and values are now two parallel arrays. Positions are indexed in a dictionary only past 8 members; below that a linear search costs no more than hashing and saves the allocation, and most JSON objects are small. Equality and hashing stay order-insensitive. Against the previous commit: Query Jayway, descendants, large: 1.76 ms -> 0.84 ms Query RFC 9535, descendants, large: 2.11 ms -> 1.30 ms Query RFC 9535, filter, large: 3.12 ms -> 2.34 ms Parse JSON, large: 9.2 ms -> 7.7 ms Encode books, large: 34.9 ms -> 30.4 ms New tests: order, lookups and removal across the 8-member boundary, order-insensitive equality and hashing at both sizes. --- Sources/JSONPath/OrderedDictionary.swift | 78 ++++++++++++++++------ Tests/JSONPathTests/JSONPathAPITests.swift | 38 +++++++++++ 2 files changed, 95 insertions(+), 21 deletions(-) diff --git a/Sources/JSONPath/OrderedDictionary.swift b/Sources/JSONPath/OrderedDictionary.swift index 001936c..18b5031 100644 --- a/Sources/JSONPath/OrderedDictionary.swift +++ b/Sources/JSONPath/OrderedDictionary.swift @@ -8,11 +8,18 @@ /// Equality and hashing are **order-insensitive**, matching JSON object semantics. public struct OrderedDictionary { public private(set) var keys: [Key] - private var storage: [Key: Value] + /// The values, in the order of ``keys``. + public private(set) var values: [Value] + /// The position of each key in ``keys`` and ``values``, once there are more than ``linearSearchLimit``; empty + /// before that, when a linear search costs no more than hashing the key and saves an allocation per object. + /// Iterating reads the two arrays and never hashes. + private var positions: [Key: Int] + static var linearSearchLimit: Int { 8 } public init() { keys = [] - storage = [:] + values = [] + positions = [:] } /// Creates an ordered dictionary from a sequence of pairs. Later duplicates win @@ -22,16 +29,27 @@ public struct OrderedDictionary { for (key, value) in elements { self[key] = value } } - public var values: [Value] { keys.map { storage[$0]! } } public var count: Int { keys.count } + + private func position(of key: Key) -> Int? { + keys.count > Self.linearSearchLimit ? positions[key] : keys.firstIndex(of: key) + } public var isEmpty: Bool { keys.isEmpty } public subscript(key: Key) -> Value? { - get { storage[key] } + get { position(of: key).map { values[$0] } } set { if let newValue { - if storage.updateValue(newValue, forKey: key) == nil { + if let position = position(of: key) { + values[position] = newValue + } else { keys.append(key) + values.append(newValue) + if keys.count == Self.linearSearchLimit + 1 { + positions = Dictionary(uniqueKeysWithValues: zip(keys, keys.indices)) + } else if keys.count > Self.linearSearchLimit + 1 { + positions[key] = keys.count - 1 + } } } else { removeValue(forKey: key) @@ -41,37 +59,43 @@ public struct OrderedDictionary { @discardableResult public mutating func removeValue(forKey key: Key) -> Value? { - guard let value = storage.removeValue(forKey: key) else { return nil } - keys.removeAll { $0 == key } - return value + guard let position = position(of: key) else { return nil } + keys.remove(at: position) + if keys.count > Self.linearSearchLimit { + positions[key] = nil + for later in keys[position...] { positions[later]! -= 1 } + } else { + positions = [:] + } + return values.remove(at: position) } - public func contains(key: Key) -> Bool { storage[key] != nil } + public func contains(key: Key) -> Bool { position(of: key) != nil } /// Calls `body` with the value for `key` in place, so a uniquely referenced value is not copied, or returns `nil` /// when there is no such key. mutating func modifyValue(forKey key: Key, _ body: (inout Value) throws -> R) rethrows -> R? { - guard let index = storage.index(forKey: key) else { return nil } - return try body(&storage.values[index]) + guard let position = position(of: key) else { return nil } + return try body(&values[position]) } /// The stored key equal to `key` and its value. (Swift `String` equality is canonical-equivalence /// based; callers that need code-point equality compare the returned key.) func entry(forKey key: Key) -> (key: Key, value: Value)? { - guard let index = storage.index(forKey: key) else { return nil } - return storage[index] + guard let position = position(of: key) else { return nil } + return (keys[position], values[position]) } public func mapValues(_ transform: (Value) throws -> T) rethrows -> OrderedDictionary { var result = OrderedDictionary() - for key in keys { result[key] = try transform(storage[key]!) } + for (key, value) in self { result[key] = try transform(value) } return result } public func compactMapValues(_ transform: (Value) throws -> T?) rethrows -> OrderedDictionary { var result = OrderedDictionary() - for key in keys { - if let value = try transform(storage[key]!) { result[key] = value } + for (key, value) in self { + if let value = try transform(value) { result[key] = value } } return result } @@ -83,7 +107,7 @@ public struct OrderedDictionary { } /// An unordered view of the contents. - public var dictionary: [Key: Value] { storage } + public var dictionary: [Key: Value] { Dictionary(uniqueKeysWithValues: zip(keys, values)) } } extension OrderedDictionary: RandomAccessCollection { @@ -94,8 +118,7 @@ extension OrderedDictionary: RandomAccessCollection { public var endIndex: Int { keys.count } public subscript(position: Int) -> Element { - let key = keys[position] - return (key, storage[key]!) + (keys[position], values[position]) } } @@ -106,11 +129,24 @@ extension OrderedDictionary: ExpressibleByDictionaryLiteral { } extension OrderedDictionary: Equatable where Value: Equatable { - public static func == (lhs: Self, rhs: Self) -> Bool { lhs.storage == rhs.storage } + public static func == (lhs: Self, rhs: Self) -> Bool { + lhs.count == rhs.count && lhs.allSatisfy { rhs[$0.key] == $0.value } + } } extension OrderedDictionary: Hashable where Value: Hashable { - public func hash(into hasher: inout Hasher) { hasher.combine(storage) } + /// Order-insensitive, like `Dictionary`'s: the members' hashes are combined with XOR, which ignores order. + public func hash(into hasher: inout Hasher) { + var members = 0 + for (key, value) in self { + var member = Hasher() + member.combine(key) + member.combine(value) + members ^= member.finalize() + } + hasher.combine(count) + hasher.combine(members) + } } extension OrderedDictionary: Sendable where Key: Sendable, Value: Sendable {} diff --git a/Tests/JSONPathTests/JSONPathAPITests.swift b/Tests/JSONPathTests/JSONPathAPITests.swift index da31f0a..d1b9fd6 100644 --- a/Tests/JSONPathTests/JSONPathAPITests.swift +++ b/Tests/JSONPathTests/JSONPathAPITests.swift @@ -266,3 +266,41 @@ struct MutationTests { #expect(NormalizedPath(["it's"]).description == #"$['it\'s']"#) } } + +@Suite("Ordered dictionary") +struct OrderedDictionaryTests { + @Test(arguments: [3, 20]) + func keepsOrderAndFindsEveryKeyAcrossSizes(count: Int) { + // Given members inserted in a scrambled order, past the linear-search limit for the larger count + let names = (0..() + for (index, name) in names.enumerated() { dictionary[name] = index } + + // When members are updated and removed, shrinking back across the limit + dictionary[names[0]] = -1 + let removed = names.prefix(count - 2).dropFirst() + for name in removed { dictionary.removeValue(forKey: name) } + + // Then order, lookups and both arrays agree + let kept = [names[0]] + names.suffix(2) + #expect(dictionary.keys == kept) + #expect(dictionary.values == [-1, count - 2, count - 1]) + #expect(kept.map { dictionary[$0] } == [-1, count - 2, count - 1]) + #expect(removed.allSatisfy { dictionary[$0] == nil && !dictionary.contains(key: $0) }) + } + + @Test(arguments: [3, 20]) + func equalityAndHashingIgnoreOrder(count: Int) { + // Given the same members in two orders + let pairs = (0.. Date: Sat, 14 Nov 2026 00:10:26 +0100 Subject: [PATCH 7/9] NormalizedPath.appending: one allocation instead of two elements + [element] allocated the one-element array and the result. Query RFC 9535, nodes with normalized paths, large: 1.06 ms -> 0.76 ms, 15 K -> 10 K mallocs --- Sources/JSONPath/NormalizedPath.swift | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Sources/JSONPath/NormalizedPath.swift b/Sources/JSONPath/NormalizedPath.swift index f7638cf..401a5fb 100644 --- a/Sources/JSONPath/NormalizedPath.swift +++ b/Sources/JSONPath/NormalizedPath.swift @@ -48,7 +48,11 @@ public struct NormalizedPath: Hashable, Sendable, Comparable, CustomStringConver } public func appending(_ element: Element) -> NormalizedPath { - NormalizedPath(elements + [element]) + var elements: [Element] = [] + elements.reserveCapacity(self.elements.count + 1) // one allocation, not one for `[element]` and one for `+` + elements.append(contentsOf: self.elements) + elements.append(element) + return NormalizedPath(elements) } /// The parent location, or `nil` for the root. From a04adc20b1fca5999aaf76b2eb3ac4aabf3fbade Mon Sep 17 00:00:00 2001 From: Jeffrey Macko Date: Sat, 14 Nov 2026 00:13:32 +0100 Subject: [PATCH 8/9] Compile each regex once per query, not once per node A filter calls match, search or =~ once per node, and every call translated the pattern and built a Regex again: compiling costs far more than matching. Each evaluation now owns a RegexCache, keyed by dialect, flags and pattern, and passes it to the function helpers. It lives as long as one values(in:) or nodes(in:) call: nothing is global or shared between threads. Query RFC 9535, every expression, large: 70.8 ms -> 15.0 ms, 363 K -> 83 K mallocs Query Jayway, every expression, large: 49.7 ms -> 9.4 ms, 239 K -> 19 K mallocs New test: one query reusing a pattern with and without flags, and under match and search, keeps each use's semantics. --- Sources/JSONPath/JaywayEvaluator.swift | 19 +++++++++---- Sources/JSONPath/JaywayFunctions.swift | 2 +- Sources/JSONPath/RFC9535Evaluator.swift | 33 ++++++++++++++-------- Sources/JSONPath/Support.swift | 15 ++++++++++ Tests/JSONPathTests/JSONPathAPITests.swift | 18 ++++++++++++ 5 files changed, 69 insertions(+), 18 deletions(-) diff --git a/Sources/JSONPath/JaywayEvaluator.swift b/Sources/JSONPath/JaywayEvaluator.swift index 6c73e64..5cbf08e 100644 --- a/Sources/JSONPath/JaywayEvaluator.swift +++ b/Sources/JSONPath/JaywayEvaluator.swift @@ -8,6 +8,7 @@ /// - Path functions (`.length()`, `.avg()`, ...) compute values; failures make the query fail. struct JaywayEvaluator { let root: JSONValue + var regexes = RegexCache() typealias Node = JSONPath.Node @@ -232,7 +233,9 @@ struct JaywayEvaluator { let exists = self.exists(query, current: current) return (exists != negated) ? .true : .false case .function(let call): - guard let value = try? RFC9535Functions.evaluateLogical(call, current: current, root: root, jayway: self) + guard + let value = try? RFC9535Functions.evaluateLogical( + call, current: current, root: root, jayway: self, regexes: regexes) else { return .error } return value ? .true : .false case .comparison(let lhs, let op, let rhs): @@ -246,7 +249,7 @@ struct JaywayEvaluator { guard let left = valueNode(lhs, current: current), let right = valueNode(rhs, current: current) else { return .error } - return JaywayValue.evaluate(left, op, right) + return JaywayValue.evaluate(left, op, right, regexes: regexes) } } @@ -268,7 +271,9 @@ struct JaywayEvaluator { return JaywayValue(value) case .function(let call): guard - let value = (try? RFC9535Functions.evaluateValue(call, current: current, root: root, jayway: self)) + let value = + (try? RFC9535Functions.evaluateValue( + call, current: current, root: root, jayway: self, regexes: regexes)) ?? nil else { return nil } return JaywayValue(value) @@ -358,7 +363,8 @@ enum JaywayValue { } static func evaluate( - _ left: JaywayValue, _ op: JSONPath.ComparisonOperator, _ right: JaywayValue + _ left: JaywayValue, _ op: JSONPath.ComparisonOperator, _ right: JaywayValue, + regexes: RegexCache = RegexCache() ) -> JaywayEvaluator.Truth { @@ -383,7 +389,10 @@ enum JaywayValue { (patternValue, subject) = (right, left) } guard case .pattern(let pattern, let flags) = patternValue else { return .error } - guard let regex = JaywayRegex.compile(pattern, flags: flags) else { return .error } + guard + let regex = regexes.regex( + "jayway:" + flags + "/" + pattern, compile: { JaywayRegex.compile(pattern, flags: flags) }) + else { return .error } guard let text = subject.regexSubject else { return .false } return truth((try? regex.firstMatch(in: text)) != nil) case .in: diff --git a/Sources/JSONPath/JaywayFunctions.swift b/Sources/JSONPath/JaywayFunctions.swift index a9e08b7..63768ec 100644 --- a/Sources/JSONPath/JaywayFunctions.swift +++ b/Sources/JSONPath/JaywayFunctions.swift @@ -116,7 +116,7 @@ enum JaywayFunctions { case .function(let call): guard let value = try RFC9535Functions.evaluateValue( - call, current: input, root: evaluator.root, jayway: evaluator) + call, current: input, root: evaluator.root, jayway: evaluator, regexes: evaluator.regexes) else { throw JSONPath.EvaluationError("Function argument did not resolve") } return value case .logical: diff --git a/Sources/JSONPath/RFC9535Evaluator.swift b/Sources/JSONPath/RFC9535Evaluator.swift index fa623a9..9226c7c 100644 --- a/Sources/JSONPath/RFC9535Evaluator.swift +++ b/Sources/JSONPath/RFC9535Evaluator.swift @@ -1,6 +1,7 @@ /// Evaluates queries with RFC 9535 semantics. struct RFC9535Evaluator { let root: JSONValue + var regexes = RegexCache() typealias Node = JSONPath.Node @@ -120,7 +121,9 @@ struct RFC9535Evaluator { let exists = !((try? evaluate(query, current: current)) ?? []).isEmpty return exists != negated case .function(let call): - return (try? RFC9535Functions.evaluateLogical(call, current: current, root: root, jayway: nil)) ?? false + return + (try? RFC9535Functions.evaluateLogical( + call, current: current, root: root, jayway: nil, regexes: regexes)) ?? false case .comparison(let lhs, let op, let rhs): return Self.compare(value(lhs, current: current), op, value(rhs, current: current)) } @@ -134,7 +137,9 @@ struct RFC9535Evaluator { guard let nodes = try? evaluate(query, current: current), nodes.count == 1 else { return nil } return nodes[0].value case .function(let call): - return (try? RFC9535Functions.evaluateValue(call, current: current, root: root, jayway: nil)) ?? nil + return + (try? RFC9535Functions.evaluateValue(call, current: current, root: root, jayway: nil, regexes: regexes)) + ?? nil case .regex: return nil } } @@ -254,9 +259,10 @@ enum RFC9535Functions { } static func arguments( - _ call: JSONPath.FunctionCall, current: JSONValue, root: JSONValue, jayway: JaywayEvaluator? + _ call: JSONPath.FunctionCall, current: JSONValue, root: JSONValue, jayway: JaywayEvaluator?, + regexes: RegexCache ) throws -> [Argument] { - let rfc = RFC9535Evaluator(root: root) + let rfc = RFC9535Evaluator(root: root, regexes: regexes) let parameters = signatures[call.name]?.parameters ?? [] return try call.arguments.enumerated().map { index, argument in let parameter = index < parameters.count ? parameters[index] : .value @@ -277,9 +283,10 @@ enum RFC9535Functions { } case .function(let inner): if resultType(of: inner) == .logical { - return .logical(try evaluateLogical(inner, current: current, root: root, jayway: jayway)) + return .logical( + try evaluateLogical(inner, current: current, root: root, jayway: jayway, regexes: regexes)) } - return .value(try evaluateValue(inner, current: current, root: root, jayway: jayway)) + return .value(try evaluateValue(inner, current: current, root: root, jayway: jayway, regexes: regexes)) case .logical(let expression): if let jayway { return .logical(jayway.accept(expression, current: current)) } return .logical(rfc.test(expression, current: current)) @@ -289,9 +296,10 @@ enum RFC9535Functions { /// Evaluates a ValueType function (`length`, `count`, `value`). `nil` is "Nothing". static func evaluateValue( - _ call: JSONPath.FunctionCall, current: JSONValue, root: JSONValue, jayway: JaywayEvaluator? + _ call: JSONPath.FunctionCall, current: JSONValue, root: JSONValue, jayway: JaywayEvaluator?, + regexes: RegexCache ) throws -> JSONValue? { - let args = try arguments(call, current: current, root: root, jayway: jayway) + let args = try arguments(call, current: current, root: root, jayway: jayway, regexes: regexes) switch call.name { case "length": guard case .value(let value?) = args.first else { return nil } @@ -314,14 +322,15 @@ enum RFC9535Functions { /// Evaluates a LogicalType function (`match`, `search`). static func evaluateLogical( - _ call: JSONPath.FunctionCall, current: JSONValue, root: JSONValue, jayway: JaywayEvaluator? + _ call: JSONPath.FunctionCall, current: JSONValue, root: JSONValue, jayway: JaywayEvaluator?, + regexes: RegexCache ) throws -> Bool { - let args = try arguments(call, current: current, root: root, jayway: jayway) + let args = try arguments(call, current: current, root: root, jayway: jayway, regexes: regexes) switch call.name { case "match", "search": guard args.count == 2, case .value(.string(let subject)?) = args[0], case .value(.string(let pattern)?) = args[1], - let regex = IRegexp.compile(pattern) + let regex = regexes.regex("i-regexp:" + pattern, compile: { IRegexp.compile(pattern) }) else { return false } let target = subject if call.name == "match" { @@ -330,7 +339,7 @@ enum RFC9535Functions { return (try? regex.firstMatch(in: target)) != nil default: // NodesType results convert to LogicalType: non-empty means true. - if let value = try evaluateValue(call, current: current, root: root, jayway: jayway) { + if let value = try evaluateValue(call, current: current, root: root, jayway: jayway, regexes: regexes) { return value.boolValue ?? true } return false diff --git a/Sources/JSONPath/Support.swift b/Sources/JSONPath/Support.swift index d717bf0..9f7612d 100644 --- a/Sources/JSONPath/Support.swift +++ b/Sources/JSONPath/Support.swift @@ -30,3 +30,18 @@ extension String { return result } } + +/// The regular expressions compiled while one query runs. A filter calls `match`, `search` or `=~` once per node, +/// nearly always with the same pattern, and compiling a pattern costs far more than matching it. One cache lives as +/// long as one evaluation, so nothing is shared between queries or threads. +final class RegexCache { + private var compiled: [String: Regex?] = [:] + + /// The regex for `key`, compiled by `compile` the first time; a pattern that does not compile is remembered too. + func regex(_ key: String, compile: () -> Regex?) -> Regex? { + if let regex = compiled[key] { return regex } + let regex = compile() + compiled[key] = .some(regex) + return regex + } +} diff --git a/Tests/JSONPathTests/JSONPathAPITests.swift b/Tests/JSONPathTests/JSONPathAPITests.swift index d1b9fd6..22f339a 100644 --- a/Tests/JSONPathTests/JSONPathAPITests.swift +++ b/Tests/JSONPathTests/JSONPathAPITests.swift @@ -72,6 +72,24 @@ struct JSONParserTests { @Suite("JSONPath API") struct JSONPathAPITests { + @Test func patternsReusedInOneQueryKeepTheirOwnFlagsAndSemantics() throws { + // Given names that differ in case and in what surrounds the pattern + let document: JSONValue = [["n": "Ab"], ["n": "ab"], ["n": "xab"], ["n": 1]] + + // When one query uses a pattern with and without flags, or under both match and search + let jayway = try JSONPath(#"$[?(@.n =~ /ab/i || @.n =~ /ab/)].n"#, dialect: .jayway).values(in: document) + let jaywayCaseSensitive = try JSONPath(#"$[?(@.n =~ /ab/ && !(@.n =~ /AB/i))].n"#, dialect: .jayway) + .values(in: document) + let rfc = try JSONPath("$[?match(@.n, 'ab') || search(@.n, 'ab')].n").values(in: document) + let rfcWhole = try JSONPath("$[?match(@.n, 'ab') && search(@.n, 'ab')].n").values(in: document) + + // Then each use keeps its own flags, and match stays whole-string while search does not + #expect(jayway == ["Ab", "ab", "xab"]) + #expect(jaywayCaseSensitive == []) + #expect(rfc == ["ab", "xab"]) + #expect(rfcWhole == ["ab"]) + } + static let store = try! JSONValue( parsing: """ {"store": {"book": [ From 6df9ad2a382bcb6ade1584bd3dd2bacc344961af Mon Sep 17 00:00:00 2001 From: Jeffrey Macko Date: Sat, 14 Nov 2026 00:16:33 +0100 Subject: [PATCH 9/9] Document the benchmarks: README section, AGENTS.md rule, format commands README, "Benchmarks": what they measure, how to run them, compare a change against main and profile one. AGENTS.md: a change made for speed or memory states its before and after. Benchmarks/ is in the format and lint commands of AGENTS.md and CONSTRAINTS.md. --- AGENTS.md | 3 ++- CONSTRAINTS.md | 2 +- README.md | 18 ++++++++++++++++++ Sources/JSONPath/Mutation.swift | 3 ++- 4 files changed, 23 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9be70af..ed050ef 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -23,8 +23,9 @@ Read `CONSTRAINTS.md` before writing code. Do not weaken it to make a change pas ## Build and test - `swift build` and `swift test`; one test with `swift test --filter /`. Pipe through `xcsift` (configured in `.xcsift.toml`) for compact errors. - CI (`.github/workflows/ci.yml`) runs macOS and Linux on Swift 6.0, 6.1 and 6.2: code must compile on 6.0 with only the standard library. -- Format before handing back Swift changes: `swift-format format --in-place --parallel --recursive Sources Tests Package.swift Architecture` (config in `.swift-format`). Use the Swift 6.3 toolchain's swift-format (`swiftly run swift-format … +6.3`): the format check runs 6.3, and other versions wrap lines differently. +- Format before handing back Swift changes: `swift-format format --in-place --parallel --recursive Sources Tests Package.swift Architecture Benchmarks` (config in `.swift-format`). Use the Swift 6.3 toolchain's swift-format (`swiftly run swift-format … +6.3`): the format check runs 6.3, and other versions wrap lines differently. - Architecture rules: `swift test --package-path Architecture` (macOS only) runs the mechanical part of `CODING_STANDARDS.md` and `CONSTRAINTS.md` as [swift-llm-check](https://github.com/mackoj/swift-llm-check) rules, listed in `docs/architecture-rules.md`. A failure prints the rule, why it exists and how to fix it: fix the code, never add a baseline. A new or changed rule needs its rationale and bad and good examples, a `DetectorTests` case, and `LLM_CHECK_RECORD=1 swift test --package-path Architecture` to regenerate the document. +- Benchmarks: `swift package --package-path Benchmarks benchmark` (package-benchmark; README, "Benchmarks"). A change made for speed or memory states its before and after from `benchmark baseline compare main` in the pull request; a change to a hot path (JSON parsing or printing, evaluation, mutation, `OrderedDictionary`) checks it did not regress. `Benchmarks/scripts/profile.sh ''` shows where a benchmark spends its time. - Pull requests also run `.github/workflows/soundness.yml`: swiftlang's soundness checks (format, DocC with warnings as errors, API breakage against the base branch, YAML lint, shellcheck, broken symlinks) plus actionlint and zizmor on the workflows. A deliberate API break is called out in the pull request. - For a differential run against Sextant, set `SEXTANT_ORACLE_LOG` as described in the README's Tests section. diff --git a/CONSTRAINTS.md b/CONSTRAINTS.md index dcb43f9..1c6262e 100644 --- a/CONSTRAINTS.md +++ b/CONSTRAINTS.md @@ -18,7 +18,7 @@ Run these before handing back a code change; each must pass. | Diff integrity | 0 whitespace errors | `git diff --check main` | | Compilation | 0 errors, debug and release | `swift build --build-tests` and `swift build -c release` | | Behaviour | 0 failing tests, including all 715 compliance cases, the Sextant suite and README examples | `swift test` | -| Formatting | 0 changes from formatting, 0 lint findings, with swift-format 6.3 | `swift-format lint --strict --parallel --recursive Sources Tests Package.swift Architecture` | +| Formatting | 0 changes from formatting, 0 lint findings, with swift-format 6.3 | `swift-format lint --strict --parallel --recursive Sources Tests Package.swift Architecture Benchmarks` | | Architecture rules | 0 findings from the rules in `docs/architecture-rules.md`, no baseline, and the rules document up to date | `swift test --package-path Architecture` (macOS) | | Public API | 0 breaking changes against the base branch, unless intended and called out in the pull request | `swift package diagnose-api-breaking-changes main` | | Documentation | 0 DocC warnings for the `.spi.yml` targets | Soundness workflow's documentation check (CI) | diff --git a/README.md b/README.md index 89b1f63..0e4dc9f 100644 --- a/README.md +++ b/README.md @@ -189,6 +189,24 @@ swift test - Set `SEXTANT_ORACLE_LOG=/path/to/file.jsonl` to record every (document, path) pair the Sextant tests evaluate, for differential testing against Sextant itself. +## Benchmarks + +Benchmarks live in `Benchmarks/`, a separate package on +[package-benchmark](https://github.com/ordo-one/package-benchmark) (see +[Swift.org's introduction](https://www.swift.org/blog/benchmarks/)), so the library never depends on it. They parse and +print JSON, parse paths in both Dialects, run queries on a generated 1.4 MB document and on the compliance suite, +resolve JSON Pointers, mutate, and decode and encode with Codable, measuring wall clock, CPU, allocations, retains and +peak memory. They need macOS 15 and jemalloc (`brew install jemalloc`). + +```sh +swift package --package-path Benchmarks benchmark +# Compare a change against main: +git switch main && swift package --package-path Benchmarks --allow-writing-to-package-directory benchmark baseline update main +git switch - && swift package --package-path Benchmarks benchmark baseline compare main +# Profile one benchmark with Instruments' Time Profiler and print its hottest functions: +Benchmarks/scripts/profile.sh 'Query RFC 9535, descendants, large' +``` + ## License MIT. See [LICENSE](LICENSE). Test fixtures keep their own licenses, as noted above. diff --git a/Sources/JSONPath/Mutation.swift b/Sources/JSONPath/Mutation.swift index 4b42e5b..4f82bf1 100644 --- a/Sources/JSONPath/Mutation.swift +++ b/Sources/JSONPath/Mutation.swift @@ -138,7 +138,8 @@ extension JSONValue { defer { value = .object(object) } if rest.isEmpty { var child = object[name] - if case .some = child { object[name] = .null } // keeps the member's position, drops the second reference + // Keeps the member's position and drops the second reference. + if case .some = child { object[name] = .null } body(&child) object[name] = child } else {