Skip to content

Commit b7413ea

Browse files
authored
Optimize DetectBest execution (#7)
1 parent ac37679 commit b7413ea

File tree

2 files changed

+25
-4
lines changed

2 files changed

+25
-4
lines changed

detector.go

+15-4
Original file line numberDiff line numberDiff line change
@@ -85,11 +85,22 @@ var (
8585

8686
// DetectBest returns the Result with highest Confidence.
8787
func (d *Detector) DetectBest(b []byte) (r *Result, err error) {
88-
var all []Result
89-
if all, err = d.DetectAll(b); err == nil {
90-
r = &all[0]
88+
input := newRecognizerInput(b, d.stripTag)
89+
outputChan := make(chan recognizerOutput)
90+
for _, r := range d.recognizers {
91+
go matchHelper(r, input, outputChan)
92+
}
93+
var output Result
94+
for i := 0; i < len(d.recognizers); i++ {
95+
o := <-outputChan
96+
if output.Confidence < o.Confidence {
97+
output = Result(o)
98+
}
99+
}
100+
if output.Confidence == 0 {
101+
return nil, NotDetectedError
91102
}
92-
return
103+
return &output, nil
93104
}
94105

95106
// DetectAll returns all Results which have non-zero Confidence. The Results are sorted by Confidence in descending order.

detector_test.go

+10
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package chardet_test
22

33
import (
4+
"bytes"
45
"github.com/gogs/chardet"
56
"io"
67
"os"
@@ -58,3 +59,12 @@ func TestDetector(t *testing.T) {
5859
}
5960
}
6061
}
62+
63+
func BenchmarkDetectBest(b *testing.B) {
64+
textDetector := chardet.NewTextDetector()
65+
aaaa := bytes.Repeat([]byte("A"), 1024)
66+
b.ReportAllocs()
67+
for i := 0; i < b.N; i++ {
68+
textDetector.DetectBest(aaaa)
69+
}
70+
}

0 commit comments

Comments
 (0)