Skip to content

Commit 69a8e73

Browse files
committed
Add Substring benchmark for naive ACSII whitespace trimming.
This is derived from swift-nio-http2's codebase, which contains this unfortunate code for trimming ASCII whitespace.
1 parent e6a375a commit 69a8e73

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

benchmark/single-source/Substring.swift

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ public let SubstringTest = [
2929
BenchmarkInfo(name: "SubstringEquatable", runFunction: run_SubstringEquatable, tags: [.validation, .api, .String]),
3030
BenchmarkInfo(name: "SubstringFromLongString", runFunction: run_SubstringFromLongString, tags: [.validation, .api, .String]),
3131
BenchmarkInfo(name: "SubstringFromLongStringGeneric", runFunction: run_SubstringFromLongStringGeneric, tags: [.validation, .api, .String]),
32+
BenchmarkInfo(name: "SubstringTrimmingASCIIWhitespace", runFunction: run_SubstringTrimmingASCIIWhitespace, tags: [.validation, .api, .String]),
3233
]
3334

3435
// A string that doesn't fit in small string storage and doesn't fit in Latin-1
@@ -267,6 +268,38 @@ public func run_SubstringComparable(_ N: Int) {
267268
CheckResults(count == N*500)
268269
}
269270

271+
extension Character {
272+
fileprivate var isASCIIWhitespace: Bool {
273+
return self == " " || self == "\t" || self == "\r" || self == "\n" || self == "\r\n"
274+
}
275+
}
276+
277+
extension Substring {
278+
fileprivate func trimWhitespace() -> Substring {
279+
var me = self
280+
while me.first?.isASCIIWhitespace == .some(true) {
281+
me = me.dropFirst()
282+
}
283+
while me.last?.isASCIIWhitespace == .some(true) {
284+
me = me.dropLast()
285+
}
286+
return me
287+
}
288+
}
289+
290+
let _trimmableSubstrings = "pineapple,🍍, pineapple\t,\r\n\r\n\r\n, 🍍 ,".split(separator: ",")
291+
292+
@inline(never)
293+
public func run_SubstringTrimmingASCIIWhitespace(_ N: Int) {
294+
let substrings = _trimmableSubstrings // bringing this alias from above
295+
var count = 0
296+
for _ in 1...N*100 {
297+
for substring in substrings {
298+
blackHole(substring.trimWhitespace())
299+
}
300+
}
301+
}
302+
270303
/*
271304
func checkLess<T, U>(_ x: T, _ y: U)
272305
where T : StringProtocol, U : StringProtocol {

0 commit comments

Comments
 (0)