github.com/AndrienkoAleksandr/go@v0.0.19/src/go/printer/performance_test.go (about) 1 // Copyright 2009 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // This file implements a simple printer performance benchmark: 6 // go test -bench=BenchmarkPrint 7 8 package printer 9 10 import ( 11 "bytes" 12 "go/ast" 13 "go/parser" 14 "go/token" 15 "io" 16 "log" 17 "os" 18 "testing" 19 ) 20 21 var ( 22 fileNode *ast.File 23 fileSize int64 24 25 declNode ast.Decl 26 declSize int64 27 ) 28 29 func testprint(out io.Writer, node ast.Node) { 30 if err := (&Config{TabIndent | UseSpaces | normalizeNumbers, 8, 0}).Fprint(out, fset, node); err != nil { 31 log.Fatalf("print error: %s", err) 32 } 33 } 34 35 // cannot initialize in init because (printer) Fprint launches goroutines. 36 func initialize() { 37 const filename = "testdata/parser.go" 38 39 src, err := os.ReadFile(filename) 40 if err != nil { 41 log.Fatalf("%s", err) 42 } 43 44 file, err := parser.ParseFile(fset, filename, src, parser.ParseComments) 45 if err != nil { 46 log.Fatalf("%s", err) 47 } 48 49 var buf bytes.Buffer 50 testprint(&buf, file) 51 if !bytes.Equal(buf.Bytes(), src) { 52 log.Fatalf("print error: %s not idempotent", filename) 53 } 54 55 fileNode = file 56 fileSize = int64(len(src)) 57 58 for _, decl := range file.Decls { 59 // The first global variable, which is pretty short: 60 // 61 // var unresolved = new(ast.Object) 62 if decl, ok := decl.(*ast.GenDecl); ok && decl.Tok == token.VAR { 63 declNode = decl 64 declSize = int64(fset.Position(decl.End()).Offset - fset.Position(decl.Pos()).Offset) 65 break 66 } 67 68 } 69 } 70 71 func BenchmarkPrintFile(b *testing.B) { 72 if fileNode == nil { 73 initialize() 74 } 75 b.ReportAllocs() 76 b.SetBytes(fileSize) 77 for i := 0; i < b.N; i++ { 78 testprint(io.Discard, fileNode) 79 } 80 } 81 82 func BenchmarkPrintDecl(b *testing.B) { 83 if declNode == nil { 84 initialize() 85 } 86 b.ReportAllocs() 87 b.SetBytes(declSize) 88 for i := 0; i < b.N; i++ { 89 testprint(io.Discard, declNode) 90 } 91 }