fix: build json dict in key order when parsing - #71
Merged
Merged
Conversation
Collect the keys while parsing an object and insert them into the sorted map in key order, instead of inserting each key as it is read. Inserting out of order into a sorted map shifts the whole tail on every insert.
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
变更
parseDict原先每读到一个键就sortedmap.Add一次。有序表插入乱序键时需要搬移整个尾部,键名降序排列时每次插入都搬移全部已有元素。改为先把键值收集到 map,循环结束后
sort.Strings排序再按序插入 —— 有序插入退化为 append,整体由 O(n²) 降为 O(n log n)。键名重复时仍是后出现者覆盖先出现者,与原行为一致。
测试
新增
parse_dict_test.go:TestParseDictKeyOrder覆盖升序/降序两种键序TestParseDictDuplicateKey确认重复键的覆盖语义未变TestParseDictManyKeys以 20 万降序键作为回归守卫(含耗时上限)BenchmarkParseDictDescendingKeys供后续观察实测 20 万降序键:修复前约 95 s,修复后 0.33 s。
go test ./...全量通过。