8000 perf: Replace O(n) slice scans with O(1) map lookups in NewKey() and NewSection() by Liudon · Pull Request #378 · go-ini/ini · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions bench_test.go
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
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package ini

import (
"fmt"
"testing"
)

Expand Down Expand Up @@ -115,6 +116,50 @@ func Benchmark_Key_SetValue_VisSection(b *testing.B) {
}
}

func Benchmark_NewKey_With_N_Keys(b *testing.B) {
for _, n := range []int{10, 100, 500, 1000} {
b.Run(fmt.Sprintf("keys=%d", n), func(b *testing.B) {
f := Empty()
sec, err := f.NewSection("bench")
if err != nil {
b.Fatal(err)
}
for i := 0; i < n; i++ {
if _, err := sec.NewKey(fmt.Sprintf("key%d", i), "val"); err != nil {
b.Fatal(err)
}
}
target := fmt.Sprintf("key%d", n-1)
b.ResetTimer()
for i := 0; i < b.N; i++ {
if _, err := sec.NewKey(target, "newval"); err != nil {
b.Fatal(err)
}
}
})
}
}

func Benchmark_NewSection_With_N_Sections(b *testing.B) {
for _, n := range []int{10, 100, 500, 1000} {
b.Run(fmt.Sprintf("sections=%d", n), func(b *testing.B) {
f := Empty()
for i := 0; i < n; i++ {
if _, err := f.NewSection(fmt.Sprintf("sec%d", i)); err != nil {
b.Fatal(err)
}
}
target := fmt.Sprintf("sec%d", n-1)
b.ResetTimer()
for i := 0; i < b.N; i++ {
if _, err := f.NewSection(target); err != nil {
b.Fatal(err)
}
}
})
}
}

func Benchmark_Key_Strings_LargeArray(b *testing.B) {
c, err := Load("testdata/large_array.ini")
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion file.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ func (f *File) NewSection(name string) (*Section, error) {
defer f.lock.Unlock()
}

if !f.options.AllowNonUniqueSections && inSlice(name, f.sectionList) {
if !f.options.AllowNonUniqueSections && f.sections[name] != nil {
return f.sections[name][0], nil
}

Expand Down
24 changes: 0 additions & 24 deletions helper.go

This file was deleted.

27 changes: 0 additions & 27 deletions helper_test.go

This file was deleted.

2 changes: 1 addition & 1 deletion section.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func (s *Section) NewKey(name, val string) (*Key, error) {
defer s.f.lock.Unlock()
}

if inSlice(name, s.keyList) {
if _, ok := s.keys[name]; ok {
if s.f.options.AllowShadows {
if err := s.keys[name].addShadow(val); err != nil {
return nil, err
Expand Down
0