Skip to content

Commit 1c07dfe

Browse files
authored
Merge pull request #813 from devlights/add-filepath-walk-walkdir-benchmark
2 parents 3d01e63 + 319c4c8 commit 1c07dfe

File tree

3 files changed

+77
-0
lines changed

3 files changed

+77
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# これは何?
2+
3+
[filepath.Walk](https://pkg.go.dev/path/filepath@go1.22.4#Walk) の説明に以下のように記載されている。
4+
5+
> Walk is less efficient than WalkDir, introduced in Go 1.16, which avoids calling os.Lstat on every visited file or directory.
6+
7+
filepath.Walk が最初から存在しているAPI。[filepath.WalkDir](https://pkg.go.dev/path/filepath@go1.22.4#WalkDir) が Go 1.16 で追加されたももの。
8+
9+
[filepath.Walk](https://pkg.go.dev/path/filepath@go1.22.4#Walk) は、訪問したリソースに対して [os.Lstat](https://pkg.go.dev/os@go1.22.4#Lstat) を呼び出すようになっているため、少し非効率であると記載されている。
10+
11+
実際にベンチマークして算出してみた。
12+
13+
```sh
14+
$ task
15+
task: [default] go test -count 3 -run '^$' -benchmem -bench .
16+
goos: linux
17+
goarch: amd64
18+
pkg: github.com/devlights/try-golang/examples/singleapp/walk_walkdir_benchmark
19+
cpu: AMD EPYC 7B13
20+
BenchmarkWalk-16 129 8551681 ns/op 629966 B/op 8957 allocs/op
21+
BenchmarkWalk-16 141 8357755 ns/op 630023 B/op 8957 allocs/op
22+
BenchmarkWalk-16 147 8338617 ns/op 630068 B/op 8957 allocs/op
23+
BenchmarkWalkDir-16 237 4763289 ns/op 348053 B/op 8205 allocs/op
24+
BenchmarkWalkDir-16 248 4924557 ns/op 348213 B/op 8205 allocs/op
25+
BenchmarkWalkDir-16 229 5093532 ns/op 348304 B/op 8205 allocs/op
26+
PASS
27+
ok github.com/devlights/try-golang/examples/singleapp/walk_walkdir_benchmark 11.160s
28+
```
29+
30+
確かに [filepath.WalkDir](https://pkg.go.dev/path/filepath@go1.22.4#WalkDir) の方が処理速度が速く、メモリ割り当ても効率的である。
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# https://taskfile.dev
2+
3+
version: '3'
4+
5+
tasks:
6+
default:
7+
cmds:
8+
- go test -count 3 -run '^$' -benchmem -bench .
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package main
2+
3+
import (
4+
"io/fs"
5+
"os"
6+
"path/filepath"
7+
"testing"
8+
)
9+
10+
const (
11+
dir = "../../../"
12+
)
13+
14+
func TestMain(m *testing.M) {
15+
err := os.Chdir(dir)
16+
if err != nil {
17+
os.Exit(1)
18+
}
19+
20+
ret := m.Run()
21+
22+
os.Exit(ret)
23+
}
24+
25+
func BenchmarkWalk(b *testing.B) {
26+
for i := 0; i < b.N; i++ {
27+
filepath.Walk(".", func(path string, info fs.FileInfo, err error) error {
28+
return nil
29+
})
30+
}
31+
}
32+
33+
func BenchmarkWalkDir(b *testing.B) {
34+
for i := 0; i < b.N; i++ {
35+
filepath.WalkDir(".", func(path string, info fs.DirEntry, err error) error {
36+
return nil
37+
})
38+
}
39+
}

0 commit comments

Comments
 (0)