From 984a26a07d372b1cad3fd01d53353a781bdbc52d Mon Sep 17 00:00:00 2001 From: Brett-Best Date: Fri, 17 Jul 2026 16:17:06 +1000 Subject: [PATCH] Avoid getcwd when the path is already absolute `absolutePathRepresentation()` returns immediately for an already-absolute path, but its default argument `FileManager.default.currentDirectoryPath` is evaluated at every call site regardless, because Swift evaluates default arguments before the callee runs. That property is not cached: each access allocates a buffer, issues a `getcwd` syscall, and builds a new String (see swift-foundation FileManager+Directories.swift), so callers that pass absolute paths pay for it needlessly. SourceKitten hits this once per file when constructing `File(pathDeferringReading:)`, so tools like SwiftLint that lint thousands of files make thousands of pointless `getcwd` calls during file discovery. In an Instruments trace of linting a ~7,000-file project this accounts for ~0.8 s of CPU on the serial pre-lint critical path. Make `rootDirectory` optional and resolve the working directory lazily, only on the relative-path branch that actually uses it. The relative-path behavior is unchanged. Co-Authored-By: Claude Fable 5 Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 2 ++ Source/SourceKittenFramework/String+SourceKitten.swift | 5 ++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6050c51d..29ef078b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,8 @@ [John Fairhurst](https://github.com/johnfairh) * Improve reporting of `sourcekitdInProc` loading failures. [Daniel Sunarjo](https://github.com/sunarjodaniel) +* Avoid `getcwd` in `absolutePathRepresentation()` for absolute paths. + [Brett Best](https://github.com/Brett-Best) #### Bug Fixes diff --git a/Source/SourceKittenFramework/String+SourceKitten.swift b/Source/SourceKittenFramework/String+SourceKitten.swift index e13e2b49..eb18c047 100644 --- a/Source/SourceKittenFramework/String+SourceKitten.swift +++ b/Source/SourceKittenFramework/String+SourceKitten.swift @@ -170,9 +170,12 @@ extension NSString { Returns self represented as an absolute path. - parameter rootDirectory: Absolute parent path if not already an absolute path. + Uses the current directory by default, evaluated only + if this path is relative. */ - public func absolutePathRepresentation(rootDirectory: String = FileManager.default.currentDirectoryPath) -> String { + public func absolutePathRepresentation(rootDirectory: String? = nil) -> String { if isAbsolutePath { return expandingTildeInPath } + let rootDirectory = rootDirectory ?? FileManager.default.currentDirectoryPath #if os(Linux) return NSURL(fileURLWithPath: NSURL.fileURL(withPathComponents: [rootDirectory, bridge()])!.path).standardizingPath!.path #else