Last active
December 14, 2024 19:11
-
-
Save pitt500/3a74a6151883b933fee3890a4fc321c6 to your computer and use it in GitHub Desktop.
Demo showed in my video https://youtu.be/KAXuZ9pGB4w
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
func benchmarkStringConversion() { | |
let dynamicString: String = "This is a string" | |
let iterations = 100_000 | |
var dynamicResult = 0 | |
let startDynamic = CFAbsoluteTimeGetCurrent() | |
for _ in 0..<iterations { | |
let utf8Data = Array(dynamicString.utf8) | |
dynamicResult += utf8Data.count | |
} | |
let endDynamic = CFAbsoluteTimeGetCurrent() | |
print("String time: \(endDynamic - startDynamic) seconds. Result: \(dynamicResult)") | |
} | |
func benchmarkStaticStringConversion() { | |
let staticString: StaticString = "This is a string" | |
let iterations = 100_000 | |
var staticResult = 0 | |
let startStatic = CFAbsoluteTimeGetCurrent() | |
for _ in 0..<iterations { | |
let utf8Pointer = staticString.utf8Start | |
let count = staticString.utf8CodeUnitCount | |
staticResult += count | |
} | |
let endStatic = CFAbsoluteTimeGetCurrent() | |
print("StaticString time: \(endStatic - startStatic) seconds. Result: \(staticResult)") | |
} | |
func run() async { | |
print("Starting benchmarks in parallel...") | |
await withTaskGroup(of: Void.self) { taskGroup in | |
taskGroup.addTask { | |
benchmarkStringConversion() | |
} | |
taskGroup.addTask { | |
benchmarkStaticStringConversion() | |
} | |
} | |
print("Benchmarks completed!") | |
} | |
// Wrap the async call in a Task when run in playground. | |
Task { | |
await run() | |
} | |
/* | |
String UTF-8 Conversion: | |
dynamicString converts to an array of UTF-8 bytes (Array(dynamicString.utf8)). | |
This operation adds significant overhead to String. | |
StaticString accesses its UTF-8 data directly via the utf8Start pointer. | |
No dynamic memory allocation is required, which demonstrates StaticString's efficiency. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment