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

时间:2015-02-11 10:15:02

标签: http templates go server go-templates

使用template包为客户端生成动态网页时速度太慢。

测试代码如下,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服务器来测试test.html,它反应非常快。

1 个答案:

答案 0 :(得分:7)

每次提交请求时都不应该解析模板!

读取文件,解析其内容并构建模板会有很长的时间延迟。此外,由于模板不会更改(变化的部分应该是参数!),您只需要阅读并解析模板一次 每次提供请求时,解析和创建模板都会在内存中生成大量值,然后将其丢弃(因为它们不会被重用),从而为垃圾收集器提供额外的工作。

在应用程序启动时解析模板,将其存储在变量中,并且只需在请求进入时执行模板。例如:

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)
    }
}