Skip to content

Commit a73e67e

Browse files
committed
Avoid additional allocation in non-sorted case
1 parent 27d76fc commit a73e67e

File tree

1 file changed

+24
-17
lines changed

1 file changed

+24
-17
lines changed

Foundation/NSJSONSerialization.swift

Lines changed: 24 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -503,21 +503,10 @@ private struct JSONWriter {
503503
writer("\n")
504504
incAndWriteIndent()
505505
}
506-
506+
507507
var first = true
508508

509-
var keys = Array(dict.keys)
510-
if sortedKeys {
511-
try keys.sort(by: { a, b in
512-
guard let a = a as? String,
513-
let b = b as? String else {
514-
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: ["NSDebugDescription" : "NSDictionary key must be NSString"])
515-
}
516-
return a < b
517-
})
518-
}
519-
520-
for key in keys {
509+
func serializeDictionaryElement(key: AnyHashable, value: Any) throws {
521510
if first {
522511
first = false
523512
} else if pretty {
@@ -526,15 +515,33 @@ private struct JSONWriter {
526515
} else {
527516
writer(",")
528517
}
529-
530-
if key is String {
531-
try serializeString(key as! String)
518+
519+
if let key = key as? String {
520+
try serializeString(key)
532521
} else {
533522
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: ["NSDebugDescription" : "NSDictionary key must be NSString"])
534523
}
535524
pretty ? writer(": ") : writer(":")
536-
try serializeJSON(dict[key]!)
525+
try serializeJSON(value)
537526
}
527+
528+
if sortedKeys {
529+
let elems = try dict.sorted(by: { a, b in
530+
guard let a = a.key as? String,
531+
let b = b.key as? String else {
532+
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: ["NSDebugDescription" : "NSDictionary key must be NSString"])
533+
}
534+
return a < b
535+
})
536+
for elem in elems {
537+
try serializeDictionaryElement(key: elem.key, value: elem.value)
538+
}
539+
} else {
540+
for (key, value) in dict {
541+
try serializeDictionaryElement(key: key, value: value)
542+
}
543+
}
544+
538545
if pretty {
539546
writer("\n")
540547
decAndWriteIndent()

0 commit comments

Comments
 (0)