From 87467ee3a573c2b13e5b0078b93cb29af7bcc545 Mon Sep 17 00:00:00 2001 From: Josh Wisenbaker Date: Fri, 13 Dec 2024 16:32:35 -0500 Subject: [PATCH 1/2] PrettyPrinterPerformance PrettyPrinterPerformance PrettyPrinterPerformance PrettyPrinterPerformance Optimized the PrettyPrinter for #894 Worked to get the perfomance to be closer to where we were before the changes in #883. This code should be only about 1.5% slower rather than 7% slower. Using a lazy filter as `count(where:_)` isn't avaliable < Swift 6.0. One forward loop and using the UTF8 view makes this faster than the original code pre-#883. --- .../PrettyPrint/PrettyPrintBuffer.swift | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/Sources/SwiftFormat/PrettyPrint/PrettyPrintBuffer.swift b/Sources/SwiftFormat/PrettyPrint/PrettyPrintBuffer.swift index 4b02d372e..0752cd916 100644 --- a/Sources/SwiftFormat/PrettyPrint/PrettyPrintBuffer.swift +++ b/Sources/SwiftFormat/PrettyPrint/PrettyPrintBuffer.swift @@ -122,16 +122,17 @@ struct PrettyPrintBuffer { // In case of comments, we may get a multi-line string. // To account for that case, we need to correct the lineNumber count. // The new column is only the position within the last line. - let lines = text.split(separator: "\n") - lineNumber += lines.count - 1 - if lines.count > 1 { - // in case we have inserted new lines, we need to reset the column - column = lines.last?.count ?? 0 - } else { - // in case it is an end of line comment or a single line comment, - // we just add to the current column - column += lines.last?.count ?? 0 + var lastLength = 0 + // We are only interested in "\n" we can use the UTF8 view and skip the grapheme clustering. + for element in text.utf8 { + if element == 10 { + lineNumber += 1 + lastLength = 0 + } else { + lastLength += 1 + } } + column += lastLength } /// Request that the given number of spaces be printed out before the next text token. From bb5b4c9b5aeaee2effc728aa496cfa2bc4da54ab Mon Sep 17 00:00:00 2001 From: Josh Wisenbaker Date: Thu, 19 Dec 2024 09:00:45 -0500 Subject: [PATCH 2/2] Update Sources/SwiftFormat/PrettyPrint/PrettyPrintBuffer.swift Co-authored-by: Alex Hoppen --- Sources/SwiftFormat/PrettyPrint/PrettyPrintBuffer.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/SwiftFormat/PrettyPrint/PrettyPrintBuffer.swift b/Sources/SwiftFormat/PrettyPrint/PrettyPrintBuffer.swift index 0752cd916..724f346b5 100644 --- a/Sources/SwiftFormat/PrettyPrint/PrettyPrintBuffer.swift +++ b/Sources/SwiftFormat/PrettyPrint/PrettyPrintBuffer.swift @@ -125,7 +125,7 @@ struct PrettyPrintBuffer { var lastLength = 0 // We are only interested in "\n" we can use the UTF8 view and skip the grapheme clustering. for element in text.utf8 { - if element == 10 { + if element == UInt8(ascii: "\n") { lineNumber += 1 lastLength = 0 } else {