7

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

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

4

1 回答 1

13

您不应该在每次提供请求时都解析模板!

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

在你的应用程序启动时解析模板,将其存储在一个变量中,你只需要在请求进来时执行模板。例如:

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)
    }
}
于 2015-02-11T11:43:26.693 回答