apple / swift-docc

Documentation compiler that produces rich API reference documentation and interactive tutorials for your Swift framework or package.
https://swift.org/documentation/docc
Apache License 2.0
1.14k stars 118 forks source link

Micro optimization for whitespace trimming of strings #945

Closed d-ronnqvist closed 3 weeks ago

d-ronnqvist commented 3 weeks ago

Bug/issue #, if applicable:

Summary

This is a micro optimization to make String/removingLeadingWhitespace() and String/removingTrailingWhitespace() faster. This difference is only measurable in micro benchmarks.


I stumbled upon this code while reviewing something else and the repeated String copying irked me.

Using micro benchmarks I could confirm that using firstIndex(where:)/ lastIndex(where:) is faster for all amounts of leading and trailing whitespace. In the graphs below, all measurements are divided by the string length.

1 leading and 1 trailing space

" \(String(repeating: "A", count: n)) "
chart-1-space

n leading and n trailing spaces

"\(String(repeating: " ", count: n))A\(String(repeating: " ", count: n))"
chart-n-spaces

0 leading and 0 trailing spaces

String(repeating: "A", count: n)

Note that green compares to red and yellow compares to blue.

chart-no-spaces

Dependencies

None

Testing

None. This isn't a change in behavior.

Checklist

Make sure you check off the following items. If they cannot be completed, provide a reason.

d-ronnqvist commented 3 weeks ago

@swift-ci please test

d-ronnqvist commented 3 weeks ago

@swift-ci please test