使用“模板”包在golang中为客户端生成dynamic网页需要花费太多时间

使用template包为客户端生成一个dynamic网页时,速度非常慢。

testing代码如下,golang 1.4.1

 http.Handle("/js/", (http.FileServer(http.Dir(webpath)))) http.Handle("/css/", (http.FileServer(http.Dir(webpath)))) http.Handle("/img/", (http.FileServer(http.Dir(webpath)))) http.HandleFunc("/test", TestHandler) func TestHandler(w http.ResponseWriter, r *http.Request) { Log.Info("Entering TestHandler ...") r.ParseForm() filename := NiConfig.webpath + "/test.html" t, err := template.ParseFiles(filename) if err != nil { Log.Error("template.ParseFiles err = %v", err) } t.Execute(w, nil) } 

根据日志,我发现t.Execute(w, nil)花了大约3秒钟,我不知道为什么它使用这么多的时间。 我也尝试过Apache服务器来testingtest.html ,它的响应速度非常快。

每次提供请求时,都不应该分析模板!

读取文件,parsing其内容并build立模板有相当长的时间延迟。 另外,由于模板不会改变(不同的部分应该是参数!),你只需要读取和parsing模板一次。
同样,每次提供请求时,parsing和创build模板会在内存中生成大量值,然后将其丢弃(因为它们不会被重用),从而为垃圾收集器提供额外的工作。

在应用程序启动时分析模板,将其存储在variables中,并且只有在请求进入时才能执行模板。例如:

 var t *template.Template func init() { filename := NiConfig.webpath + "/test.html" t = template.Must(template.ParseFiles(filename)) http.HandleFunc("/test", TestHandler) } func TestHandler(w http.ResponseWriter, r *http.Request) { Log.Info("Entering TestHandler ...") // Template is ready, just Execute it if err := t.Execute(w, nil); err != nil { log.Printf("Failed to execute template: %v", err) } }