Skip to content

Commit 87467ee

Browse files
committed
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.
1 parent a871b81 commit 87467ee

File tree

1 file changed

+10
-9
lines changed

1 file changed

+10
-9
lines changed

Diff for: Sources/SwiftFormat/PrettyPrint/PrettyPrintBuffer.swift

+10-9
Original file line numberDiff line numberDiff line change
@@ -122,16 +122,17 @@ struct PrettyPrintBuffer {
122122
// In case of comments, we may get a multi-line string.
123123
// To account for that case, we need to correct the lineNumber count.
124124
// The new column is only the position within the last line.
125-
let lines = text.split(separator: "\n")
126-
lineNumber += lines.count - 1
127-
if lines.count > 1 {
128-
// in case we have inserted new lines, we need to reset the column
129-
column = lines.last?.count ?? 0
130-
} else {
131-
// in case it is an end of line comment or a single line comment,
132-
// we just add to the current column
133-
column += lines.last?.count ?? 0
125+
var lastLength = 0
126+
// We are only interested in "\n" we can use the UTF8 view and skip the grapheme clustering.
127+
for element in text.utf8 {
128+
if element == 10 {
129+
lineNumber += 1
130+
lastLength = 0
131+
} else {
132+
lastLength += 1
133+
}
134134
}
135+
column += lastLength
135136
}
136137

137138
/// Request that the given number of spaces be printed out before the next text token.

0 commit comments

Comments
 (0)