Skip to content

Commit

Permalink
Improving the performance of toJSONString in CRDTTree
Browse files Browse the repository at this point in the history
  • Loading branch information
humdrum committed Aug 1, 2024
1 parent 10b1870 commit d6dc6b1
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 24 deletions.
40 changes: 16 additions & 24 deletions Sources/Document/CRDT/CRDTTree.swift
Original file line number Diff line number Diff line change
Expand Up @@ -487,34 +487,26 @@ final class CRDTTreeNode: IndexTreeNode {
}

var toJSONString: String {
if self.type == DefaultTreeNodeType.text.rawValue {
return "{\"type\":\(self.type.toJSONString),\"value\":\((self.value as String).toJSONString)}"
} else {
var childrenString = ""
if children.isEmpty == false {
childrenString = children.compactMap { $0.toJSONString }.joined(separator: ",")
}

var resultString = "{\"type\":\(self.type.toJSONString),\"children\":[\(childrenString)]"

if let attributes = self.attrs?.toObject().mapValues({ $0.value }), attributes.isEmpty == false {
let sortedKeys = attributes.keys.sorted()

let attrsString = sortedKeys.compactMap { key in
if let value = attributes[key] {
return "\(key.toJSONString):\(value)"
} else {
return nil
}
}.joined(separator: ",")
if let data = try? JSONSerialization.data(withJSONObject: toDictionary, options: [.sortedKeys]),
let result = String(data: data, encoding: .utf8)
{
return result
}

resultString += ",\"attributes\":{\(attrsString)}"
}
return "{}"
}

resultString += "}"
var toDictionary: [String: Any] {
var dictionary: [String: Any] = ["type": self.type]

return resultString
if self.type == DefaultTreeNodeType.text.rawValue {
dictionary["value"] = self.value as String
} else {
dictionary["children"] = self.children.map { $0.toDictionary }
dictionary["attributes"] = self.attrs?.toDictionary
}

return dictionary
}

/**
Expand Down
7 changes: 7 additions & 0 deletions Sources/Document/CRDT/RHT.swift
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,13 @@ class RHT {
return result
}

var toDictionary: [String: Any] {
self.nodeMapByKey.compactMapValues { node -> Any? in
guard !node.isRemoved else { return nil }
return try? JSONSerialization.jsonObject(with: Data(node.value.utf8), options: .fragmentsAllowed)
}
}

/**
* `purge` purges the given child node.
*/
Expand Down

0 comments on commit d6dc6b1

Please sign in to comment.