From c0b805c7dc712d7397ff1c76ae1ac6211a910e50 Mon Sep 17 00:00:00 2001 From: Benjamin Radovsky Date: Tue, 27 Dec 2016 17:37:31 +1100 Subject: [PATCH] greatly optimize the *Selection.Text method and highly reduce it's amount of allocations per op. --- property.go | 33 +++++++++++++++------------------ 1 file changed, 15 insertions(+), 18 deletions(-) diff --git a/property.go b/property.go index 4cb9c04..411126d 100644 --- a/property.go +++ b/property.go @@ -63,9 +63,22 @@ func (s *Selection) Text() string { var buf bytes.Buffer // Slightly optimized vs calling Each: no single selection object created - for _, n := range s.Nodes { - buf.WriteString(getNodeText(n)) + var f func(*html.Node) + f = func(n *html.Node) { + if n.Type == html.TextNode { + // Keep newlines and spaces, like jQuery + buf.WriteString(n.Data) + } + if n.FirstChild != nil { + for c := n.FirstChild; c != nil; c = c.NextSibling { + f(c) + } + } } + for _, n := range s.Nodes { + f(n) + } + return buf.String() } @@ -192,22 +205,6 @@ func (s *Selection) ToggleClass(class ...string) *Selection { return s } -// Get the specified node's text content. -func getNodeText(node *html.Node) string { - if node.Type == html.TextNode { - // Keep newlines and spaces, like jQuery - return node.Data - } else if node.FirstChild != nil { - var buf bytes.Buffer - for c := node.FirstChild; c != nil; c = c.NextSibling { - buf.WriteString(getNodeText(c)) - } - return buf.String() - } - - return "" -} - func getAttributePtr(attrName string, n *html.Node) *html.Attribute { if n == nil { return nil