Skip to content

Instantly share code, notes, and snippets.

@chrisbrandow
Created September 1, 2017 19:57
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 chrisbrandow/a162fc012c95ea03960538c1f87096b7 to your computer and use it in GitHub Desktop.
Save chrisbrandow/a162fc012c95ea03960538c1f87096b7 to your computer and use it in GitHub Desktop.
benchmarking String vs. Data reading and processing.
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