Benchmarking.swift (2215B)
1 // 2 // Benchmarking.swift 3 // damusTests 4 // 5 // Created by William Casarin on 3/6/25. 6 // 7 8 import Testing 9 import XCTest 10 @testable import damus 11 12 class BenchmarkingTests: XCTestCase { 13 14 // Old regex-based implementations for comparison 15 func trim_suffix_regex(_ str: String) -> String { 16 return str.replacingOccurrences(of: "\\s+$", with: "", options: .regularExpression) 17 } 18 19 func trim_prefix_regex(_ str: String) -> String { 20 return str.replacingOccurrences(of: "^\\s+", with: "", options: .regularExpression) 21 } 22 23 // Test strings with different characteristics 24 lazy var testStrings: [String] = [ 25 " Hello World ", // Simple whitespace 26 " \n\t Hello World \n\t ", // Mixed whitespace 27 String(repeating: " ", count: 1000) + "Hello", // Large prefix 28 "Hello" + String(repeating: " ", count: 1000), // Large suffix 29 String(repeating: " ", count: 500) + "Hello" + String(repeating: " ", count: 500) // Both 30 ] 31 32 func testTrimSuffixRegexPerformance() throws { 33 measure { 34 for str in testStrings { 35 _ = trim_suffix_regex(str) 36 } 37 } 38 } 39 40 func testTrimSuffixNewPerformance() throws { 41 measure { 42 for str in testStrings { 43 _ = trim_suffix(str) 44 } 45 } 46 } 47 48 func testTrimPrefixRegexPerformance() throws { 49 measure { 50 for str in testStrings { 51 _ = trim_prefix_regex(str) 52 } 53 } 54 } 55 56 func testTrimPrefixNewPerformance() throws { 57 measure { 58 for str in testStrings { 59 _ = trim_prefix(str) 60 } 61 } 62 } 63 64 func testTrimFunctionCorrectness() throws { 65 // Verify that both implementations produce the same results 66 for str in testStrings { 67 XCTAssertEqual(trim_suffix(str), trim_suffix_regex(str), "New trim_suffix implementation produces different results") 68 XCTAssertEqual(trim_prefix(str), trim_prefix_regex(str), "New trim_prefix implementation produces different results") 69 } 70 } 71 } 72