Created
January 19, 2016 05:20
-
-
Save Catfish-Man/af3598101c002030612f to your computer and use it in GitHub Desktop.
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 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