-
Notifications
You must be signed in to change notification settings - Fork 17.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
html/template: escapeTemplate is inefficient #10605
Comments
escapeTemplate
/cc @robpike |
I could reproduce by generating a HTML template including numerous "<textarea>" elements. It does not seem very difficult to fix. I'm working on it. |
I don't know why, but this doesn't seem limited to "textarea", etc. elements. I think Here is a benchmark of a contrived template. It is formed by concatenating a bunch of wikipedia articles surrounded by "if" statements:
This benchmark took 35s to run once on my machine. |
Here is my stab at a faster
This takes advantage of the fact that each marker starts with This dropped the same benchmark from 35s down to 0.45s. |
Here is my version:
I'm preparing a CL. |
CL https://golang.org/cl/9502 mentions this issue. |
I have been profiling the execution of our templates using the "html/template" package.
The time to parse and execute a template was around 100ms. I realize that the first time the template is executed, "html/template" escapes it using the internal
escapeTemplate()
function. Still it seemed extremely slow to me.Using the "pprof" tool, I found the culprit:
That seems like a lot of time spent lower-casing a string. By inserting a counter into the
tSpecialTagEnd
function, I found out thatstrings.ToLower
is being called 4320 times per request.The offending function looks like this:
It occurs to me that:
s
is cast to a string each time (new memory allocation)specialTagEndMarker
tSpecialTagEnd
increases linearly with file size, the time complexity is O(n^2)The time complexity could be reduced to O(n) by either:
It also seems unnecessary to use the
strings
package when thebytes
package can lower-case just fine. This would save an allocation.I tried another template file that was over 1MB (about 20 html documents surrounded by "if" statements), and the
ExecuteTemplate
function took 20 seconds.The text was updated successfully, but these errors were encountered: