Skip to content

perf: Replace O(n) slice scans with O(1) map lookups in NewKey() and NewSection()#378

Open
Liudon wants to merge 1 commit intogo-ini:mainfrom
Liudon:fix/optimize-newkey-newsection-lookup
Open

perf: Replace O(n) slice scans with O(1) map lookups in NewKey() and NewSection()#378
Liudon wants to merge 1 commit intogo-ini:mainfrom
Liudon:fix/optimize-newkey-newsection-lookup

Conversation

@Liudon
Copy link
Copy Markdown

@Liudon Liudon commented Apr 9, 2026

Describe the pull request

Fixes #377

Changes

Replace inSlice() linear scan with direct map lookup in two hot paths:

section.go — NewKey()

- if inSlice(name, s.keyList) {
+ if _, ok := s.keys[name]; ok {

file.go — NewSection()

- if !f.options.AllowNonUniqueSections && inSlice(name, f.sectionList) {
+ if !f.options.AllowNonUniqueSections && f.sections[name] != nil {

Both slices (keyList, sectionList) are always kept in sync with their
corresponding maps (keys, sections), so the semantics are unchanged.

Benchmark

Added Benchmark_NewKey_With_N_Keys and Benchmark_NewSection_With_N_Sections
to verify the improvement.

Before (O(n) — linear growth):

NewKey/keys=10       51 ns/op    0 allocs/op
NewKey/keys=100     217 ns/op    0 allocs/op
NewKey/keys=500     828 ns/op    0 allocs/op
NewKey/keys=1000   1722 ns/op    0 allocs/op

NewSection/sections=10       35 ns/op    0 allocs/op
NewSection/sections=100     204 ns/op    0 allocs/op
NewSection/sections=500     830 ns/op    0 allocs/op
NewSection/sections=1000   1695 ns/op    0 allocs/op

After (O(1) — constant time):

NewKey/keys=10       40 ns/op    0 allocs/op
NewKey/keys=100      46 ns/op    0 allocs/op
NewKey/keys=500      50 ns/op    0 allocs/op
NewKey/keys=1000     40 ns/op    0 allocs/op

NewSection/sections=10       23 ns/op    0 allocs/op
NewSection/sections=100      23 ns/op    0 allocs/op
NewSection/sections=500      21 ns/op    0 allocs/op
NewSection/sections=1000     30 ns/op    0 allocs/op

At 1000 keys/sections: ~43x faster for NewKey, ~57x faster for NewSection.

Checklist

  • I agree to follow the Code of Conduct by submitting this pull request.
  • I have read and acknowledge the Contributing guide.
  • I have added test cases to cover the new code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf: NewKey() and NewSection() use O(n) linear scan for existence check

1 participant