Skip to content

Commit 42f9cb0

Browse files
committed
refactor(htmlio): optimize HTML tag writing with stack-allocated buffer
1 parent 8e83d1a commit 42f9cb0

1 file changed

Lines changed: 20 additions & 13 deletions

File tree

lib/htmlio/writehtml.go

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ var singletonTags = map[string]struct{}{
2727
"wbr": {},
2828
}
2929

30+
const htmlBufferSize = 128
31+
3032
func needClosingTag(tag string) bool {
3133
_, ok := singletonTags[tag]
3234
return !ok
@@ -42,10 +44,8 @@ func appendAttrs(b []byte, attrs []template.HTMLAttr) []byte {
4244
return b
4345
}
4446

45-
// WriteHTMLTag writes an HTML start tag with optional id, type, value and raw
46-
// attribute fragments.
47-
func WriteHTMLTag(w io.Writer, jid jid.Jid, htmlTag, typeAttr, valueAttr string, attrs []template.HTMLAttr) (err error) {
48-
b := jid.AppendStartTagAttr(nil, htmlTag)
47+
func appendHTMLTag(b []byte, jid jid.Jid, htmlTag, typeAttr, valueAttr string, attrs []template.HTMLAttr) []byte {
48+
b = jid.AppendStartTagAttr(b, htmlTag)
4949
if typeAttr != "" {
5050
b = append(b, ` type=`...)
5151
b = strconv.AppendQuote(b, typeAttr)
@@ -56,6 +56,14 @@ func WriteHTMLTag(w io.Writer, jid jid.Jid, htmlTag, typeAttr, valueAttr string,
5656
}
5757
b = appendAttrs(b, attrs)
5858
b = append(b, '>')
59+
return b
60+
}
61+
62+
// WriteHTMLTag writes an HTML start tag with optional id, type, value and raw
63+
// attribute fragments.
64+
func WriteHTMLTag(w io.Writer, jid jid.Jid, htmlTag, typeAttr, valueAttr string, attrs []template.HTMLAttr) (err error) {
65+
var buf [htmlBufferSize]byte
66+
b := appendHTMLTag(buf[:0], jid, htmlTag, typeAttr, valueAttr, attrs)
5967
_, err = w.Write(b)
6068
return
6169
}
@@ -71,15 +79,14 @@ func WriteHTMLInput(w io.Writer, jid jid.Jid, typeAttr, valueAttr string, attrs
7179
// Singleton tags such as img and input are written without closing tags unless
7280
// innerHTML is non-empty.
7381
func WriteHTMLInner(w io.Writer, jid jid.Jid, htmlTag, typeAttr string, innerHTML template.HTML, attrs ...template.HTMLAttr) (err error) {
74-
if err = WriteHTMLTag(w, jid, htmlTag, typeAttr, "", attrs); err == nil {
75-
if innerHTML != "" || needClosingTag(htmlTag) {
76-
var b []byte
77-
b = append(b, innerHTML...)
78-
b = append(b, "</"...)
79-
b = append(b, htmlTag...)
80-
b = append(b, '>')
81-
_, err = w.Write(b)
82-
}
82+
var buf [htmlBufferSize]byte
83+
b := appendHTMLTag(buf[:0], jid, htmlTag, typeAttr, "", attrs)
84+
if innerHTML != "" || needClosingTag(htmlTag) {
85+
b = append(b, innerHTML...)
86+
b = append(b, "</"...)
87+
b = append(b, htmlTag...)
88+
b = append(b, '>')
8389
}
90+
_, err = w.Write(b)
8491
return
8592
}

0 commit comments

Comments
 (0)