From 4b147028feaa88243ba33d6d317cea02d2ea552a Mon Sep 17 00:00:00 2001 From: Tae Won Ha Date: Tue, 13 Sep 2022 21:08:27 +0200 Subject: [PATCH] Use a private function instead of a public extension. It's way faster. --- NvimView/Sources/NvimView/NvimView+Draw.swift | 38 ++++++++++++++++++- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/NvimView/Sources/NvimView/NvimView+Draw.swift b/NvimView/Sources/NvimView/NvimView+Draw.swift index 126e8594..2d86be13 100644 --- a/NvimView/Sources/NvimView/NvimView+Draw.swift +++ b/NvimView/Sources/NvimView/NvimView+Draw.swift @@ -222,8 +222,7 @@ extension NvimView { columnRange: ClosedRange ) -> [AttributesRun] { rowRange.map { row in - self.ugrid.cells[row][columnRange] - .groupedRanges(with: { cell in cell.attrId }) + groupedRanges(of: self.ugrid.cells[row][columnRange]) .compactMap { range in let cells = self.ugrid.cells[row][range] @@ -273,3 +272,38 @@ private let infoTextAttrs = [ ] private let colorSpace = NSColorSpace.sRGB + +/// When we use the following private function instead of the public extension function in +/// Commons.FoundationCommons.swift.groupedRanges(with:), then, according to Instruments +/// the percentage of the function is reduced from ~ 15% to 0%. +/// Keep the logic in sync with Commons.FoundationCommons.swift.groupedRanges(with:). Tests are +/// present in Commons lib. +private func groupedRanges(of cells: ArraySlice) -> [ClosedRange] { + if cells.isEmpty { return [] } + if cells.count == 1 { return [cells.startIndex...cells.startIndex] } + + var result = [ClosedRange]() + result.reserveCapacity(cells.count / 2) + + let inclusiveEndIndex = cells.endIndex - 1 + var lastStartIndex = cells.startIndex + var lastEndIndex = cells.startIndex + var lastMarker = cells.first!.attrId // cells is not empty! + for i in cells.startIndex..