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

cat*_*mia 5 templates http go go-templates server

使用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)
}
Run Code Online (Sandbox Code Playgroud)

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

icz*_*cza 9

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

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

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

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)
    }
}
Run Code Online (Sandbox Code Playgroud)