Skip to content

Instantly share code, notes, and snippets.

@Catfish-Man
Created January 19, 2016 05:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Catfish-Man/af3598101c002030612f to your computer and use it in GitHub Desktop.
Save Catfish-Man/af3598101c002030612f to your computer and use it in GitHub Desktop.
import Foundation
func measure(work:Void->Void) {
let start = NSDate()
for _ in 0..<100000 {
work()
}
let elapsed = -(start.timeIntervalSinceNow)
print(elapsed)
}
func testStringLoopWithIndexSuccessor()
{
let str = "some really long string"
let end = str.endIndex
var idx = str.startIndex
while idx < end
{
let char = str[idx]
// ... do some stuff
idx = idx.successor()
}
}
func testStringLoopWithAdvancedBy()
{
let str = "some really long string"
let len = str.characters.count
var idx = 0
while idx < len
{
let char = str[str.startIndex.advancedBy(idx)]
// ... do some stuff
idx = idx + 1
}
}
func testStringLoopWithIndexSuccessorAndUnicodeScalarView()
{
let str = "some really long string"
let sca = str.unicodeScalars
let end = sca.endIndex
var idx = sca.startIndex
while idx < end
{
let char = sca[idx]
// ... do some stuff
idx = idx.successor()
}
}
func testStringLoopWithAdvancedByAndUnicodeScalarView()
{
let str = "some really long string"
let sca = str.unicodeScalars
let len = sca.count
var idx = 0
while idx < len
{
let char = sca[sca.startIndex.advancedBy(idx)]
// ... do some stuff
idx = idx + 1
}
}
measure { testStringLoopWithAdvancedByAndUnicodeScalarView() }
measure { testStringLoopWithIndexSuccessorAndUnicodeScalarView() }
measure { testStringLoopWithAdvancedBy() }
measure { testStringLoopWithIndexSuccessor() }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment