Created
September 1, 2017 19:57
-
-
Save chrisbrandow/a162fc012c95ea03960538c1f87096b7 to your computer and use it in GitHub Desktop.
benchmarking String vs. Data reading and processing.
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
func strings(from name: String) -> [String]? { | |
let date = Date() | |
guard let path = Bundle.main.path(forResource: name, ofType: "yaml") else { | |
return nil | |
} | |
do { | |
let fileString = try String(contentsOfFile: path, encoding: .utf8) | |
let fileTime = date.timeIntervalSinceNow | |
let lines = fileString.components(separatedBy:"\n") | |
let end = date.timeIntervalSinceNow | |
print("strings from \(fileTime) -- \(end)") | |
return lines | |
} catch { | |
return nil | |
} | |
} | |
func bytes(from file: String) { | |
let start = Date() | |
guard let path = Bundle.main.path(forResource: file, ofType: "yaml") else { return } | |
offsets = [Int]() | |
do { | |
words = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped) | |
let fileTime = start.timeIntervalSinceNow | |
let bytesPtr = (words as NSData?)!.bytes | |
let newLine = UInt8(10) | |
var cur = 0 | |
let end = words!.count | |
while cur < end { | |
if (bytesPtr.advanced(by: cur).assumingMemoryBound(to: UInt8.self).pointee == newLine) { | |
offsets!.append(cur + 1) | |
} | |
cur += 1 | |
} | |
offsets!.append(end) | |
let stop = start.timeIntervalSinceNow | |
print("bytes from \(fileTime) -- \(stop)") | |
} catch { | |
print("fail url") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment