Created
December 29, 2017 19:09
-
-
Save raphlinus/6b0a7c54b563d9fe3b0cd1a1c87f9357 to your computer and use it in GitHub Desktop.
Simple JSON task using Objective-C data structures
This file contains 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
// Copyright 2017 Google LLC | |
// | |
// Licensed under the Apache License, Version 2.0 (the "License"); | |
// you may not use this file except in compliance with the License. | |
// You may obtain a copy of the License at | |
// | |
// https://www.apache.org/licenses/LICENSE-2.0 | |
// | |
// Unless required by applicable law or agreed to in writing, software | |
// distributed under the License is distributed on an "AS IS" BASIS, | |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
// See the License for the specific language governing permissions and | |
// limitations under the License. | |
import Foundation | |
var baseTs: UInt64 = 0 | |
func ts(_ label: String) { | |
let ts = mach_absolute_time() | |
print(label + String(format: ": %.3f", Double(ts - baseTs) * 1e-6)) | |
} | |
let data = try Data(contentsOf: URL(fileURLWithPath: "/tmp/update.json")) | |
func benchObjCLike() throws { | |
baseTs = mach_absolute_time() | |
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) | |
ts("after json ser") | |
let obj = json as! NSDictionary | |
ts("after cast") | |
let params = obj["params"] as! NSDictionary | |
ts("after nsdict lookup") | |
let update = params["update"] as! NSDictionary | |
ts("after lookup2") | |
let ops = update["ops"] as! NSArray | |
ts("after lookup3") | |
var total = 0 | |
var textlen = 0 | |
for opRaw in ops { | |
let op = opRaw as! NSDictionary | |
let opcode = op["op"] as! String | |
total += op["n"] as! Int | |
if opcode == "ins" { | |
let lines = op["lines"] as! NSArray | |
for lineRaw in lines { | |
let line = lineRaw as! NSDictionary | |
textlen += (line["text"] as? String)?.count ?? 0 | |
} | |
} | |
} | |
ts("after sum n") | |
print("ObjC-like result:", total, textlen) | |
} | |
try benchObjCLike() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment