Skip to content

Instantly share code, notes, and snippets.

@arsonistgopher
Created December 5, 2018 17:07
Show Gist options
  • Save arsonistgopher/1a9ea2de11c8ac4f2ee3a2ba46a23d86 to your computer and use it in GitHub Desktop.
Save arsonistgopher/1a9ea2de11c8ac4f2ee3a2ba46a23d86 to your computer and use it in GitHub Desktop.
XML benchmarks for xpath versus compact struct
package main
import (
"encoding/xml"
"fmt"
"io"
"strings"
"testing"
"github.com/antchfx/xmlquery"
)
// VLAN1 struct
type VLAN1 struct {
XMLName xml.Name `xml:"vlan"`
Name string `xml:"name"`
Desc string `xml:"description"`
ID string `xml:"vlan-id"`
}
// VLAN2 struct
type VLAN2 struct {
XMLName xml.Name `xml:"configuration"`
VLAN struct {
XMLName xml.Name `xml:"vlan"`
Name string `xml:"name"`
Desc string `xml:"description"`
ID string `xml:"vlan-id"`
} `xml:"groups>vlans>vlan"`
}
const s = `<configuration xmlns="http://xml.juniper.net/xnm/1.1/xnm" junos:changed-seconds="1328506003">
<groups>
<name>customerXY</name>
<vlans>
<vlan>
<name>VLAN100</name>
<description>Customer-XYZ-28-11-2018</description>
<vlan-id>100</vlan-id>
</vlan>
</vlans>
</groups>
</configuration>`
func Benchmark1(b *testing.B) {
for i := 0; i < b.N; i++ {
var r io.Reader
r = strings.NewReader(s)
root, err := xmlquery.Parse(r)
if err != nil {
panic(err)
}
var n *xmlquery.Node
n = xmlquery.FindOne(root, "//configuration/groups/vlans/vlan")
d := n.OutputXML(true)
xml1 := VLAN1{}
err = xml.Unmarshal([]byte(d), &xml1)
if err != nil {
fmt.Print(err)
}
}
// fmt.Printf("%+v\n", xml1)
}
func Benchmark2(b *testing.B) {
for i := 0; i < b.N; i++ {
cfgData1 := VLAN2{}
err := xml.Unmarshal([]byte(s), &cfgData1)
if err != nil {
fmt.Print(err)
}
// fmt.Printf("%+v\n", cfgData1)
}
}
@zhengchun
Copy link

I read your article XML Unmarshal and XPath, good article. In fact, xmlquery is a query package for XML, help people extract data from XML by XPath.

//d := n.OutputXML(true)
xml1 := VLAN1{}
xml1.Name = n.SelectElement("name").InnerText()
xml1.ID = n.SelectElement("vlan-id").InnerText()
xml1.Desc = n.SelectElement("description").InnerText()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment