Skip to content
Open
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
4 changes: 4 additions & 0 deletions wordcount bench/benchmark_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ func BenchmarkCountWords(b *testing.B) {
countWords(bytes)
}

func BenchmarkFastestCountWords(b *testing.B) {
fastestCountWords("test_data.txt")
}

func BenchmarkByteCountWordsV2(b *testing.B) {
f, err := os.Open("test_data.txt")
if err != nil {
Expand Down
30 changes: 30 additions & 0 deletions wordcount bench/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@ func main() {
var wordCount = countWords(bytes)
fmt.Printf("countWords: %d words, duration: %dns\n", wordCount, time.Since(start)/1000)

start = time.Now()
wordCount, err := fastestCountWords(filePath)
if err != nil {
fmt.Printf("%d", err)
}
fmt.Printf("fastestCounWords: %d words, duration: %dns\n", wordCount, time.Since(start)/1000)

start = time.Now()
f, err := os.Open(os.Args[1])
if err != nil {
Expand All @@ -45,6 +52,29 @@ func ReadFile(filePath string) ([]byte, error) {
return bytes, nil
}

// Producing the most generalizable and fast word count
func fastestCountWords(filePath string) (int, error) {
fd, err := os.Open(filePath)
if err != nil {
return 0, fmt.Errorf("could not open file %q: %v", filePath, err)
}
defer fd.Close()

words := 0
scanner := bufio.NewScanner(fd)
scanner.Split(bufio.ScanWords)

for scanner.Scan() {
words++
}

if err := scanner.Err(); err != nil {
return 0, fmt.Errorf("error reading file %q: %v", filePath, err)
}

return words, nil
}

func countWords(bytes []byte) int {
text := string(bytes)
words := strings.Fields(text)
Expand Down