Created
July 3, 2025 13:14
-
-
Save nyan-lin-tun/f7c37b7cc8c13a7816464ed4f2a7b91c to your computer and use it in GitHub Desktop.
Performance comparison between Array index and index(_, offsetBy: _)
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 | |
| let word = String(repeating: "abcde", count: 200_000) // 1,000,000 characters | |
| let k = 999_999 // Access near the end | |
| // MARK: - String.Index approach | |
| let startIndexMethod = CFAbsoluteTimeGetCurrent() | |
| let index = word.index(word.startIndex, offsetBy: k) | |
| let charFromIndex = word[index] | |
| let endIndexMethod = CFAbsoluteTimeGetCurrent() | |
| let indexDuration = endIndexMethod - startIndexMethod | |
| print("Character using String.Index: \(charFromIndex)") | |
| print("Time using String.Index: \(indexDuration) seconds") | |
| // MARK: - Array(word)[k] approach | |
| let startArrayMethod = CFAbsoluteTimeGetCurrent() | |
| let arrayWord = Array(word) | |
| let charFromArray = arrayWord[k] | |
| let endArrayMethod = CFAbsoluteTimeGetCurrent() | |
| let arrayDuration = endArrayMethod - startArrayMethod | |
| print("Character using Array: \(charFromArray)") | |
| print("Time using Array(word): \(arrayDuration) seconds") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment