Skip to content

Instantly share code, notes, and snippets.

@nyan-lin-tun
Created July 3, 2025 13:14
Show Gist options
  • Select an option

  • Save nyan-lin-tun/f7c37b7cc8c13a7816464ed4f2a7b91c to your computer and use it in GitHub Desktop.

Select an option

Save nyan-lin-tun/f7c37b7cc8c13a7816464ed4f2a7b91c to your computer and use it in GitHub Desktop.
Performance comparison between Array index and index(_, offsetBy: _)
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