Saturday, May 01, 2010

XSLT copies and sequences

And yet another post! Is it a trend or an aberration? Only time will tell.

In a previous post, I offered some solutions for problems that arise from having to deal with nodes that are functionally identical, yet still different. Sort of how two cars can be absolutely identical in terms of brand, model, year, color, etc. and yet still remain two distinct cars. (Just try to argue with the tax man that those two identical cars are actually one and the same.)

This problem can arise very easily when you deal with variables in XSLT. Consider the following:

<xsl:variable name="foo">
  <a/>
<xsl:variable>

<xsl:variable name="bar">
  <a/>
<xsl:variable>

If you compare the nodes in these variables with "$foo/a is $bar/a", the result will be "false", indicating that while these nodes may look awfully identical, XPath doesn't consider them to be the same node. And XPath does have a point, because these <a> elements will be distinct copies in memory.

In fact, you may not realize just how many copies your XSLTs are making. It's not just these hard coded bits of XML in variables, it's also any time you use an xsl:copy, xsl:copy-of, or xsl:element, as well as when you use included content in an xsl:variable, xsl:param, or xsl:with-param without a type declaration. (And some other, less common constructs as well.)

Not only can this be most inconvenient (for instance when you want to use set operators), but you may also be wasting machine resources in your performance critical application.

Fortunately, it's relatively easy to reduce the number of copies. You just have to know the tricks of the trade. And those are just what I'm going to tell you right now.

Don't duplicate hard coded XML content
Whenever you have hard coded XML content, this will result in nodes being created. If you create the same XML content in multiple places (such as we did in the foo and bar variables earlier), those will be duplicates. We could have avoided this by just copying foo to bar, like so:

<xsl:variable name="bar" select="$foo">

Now XSLT will create a new node for foo, but not for bar, as the latter will simply point to the same node that was already created for foo.

Replace xsl:copy-of with xsl:sequence
Unlike xsl:copy-of, xsl:sequence can return existing nodes. And since everything is a sequence anyway in XSLT 2.0 (including the result of xsl:copy-of), there's really no reason to not just use xsl:sequence instead of xsl:copy-of. The same goes for xsl:copy's without children, but those tend to be uncommon.

So rather than this:
<xsl:copy-of select="//baz">

Use this:
<xsl:sequence select="//baz">

Simple!

Make sure xsl:variable, xsl:param, xsl:with-param have either a "select" or an "as" attribute (or both)
The elements xsl:variable, xsl:param, xsl:with-param always make a copy, unless you specify either the "select" attribute, or the "as" attribute (or both).

Whenever possible, use the select attribute, as in those cases you'll never get a copy. If that's not possible, and you really do have to use the element content, you can specify the variable's type with the "as" attribute. In such a case, XSLT will not force the copy to be make. However, if you use hard coded XML, or an xsl:copy-of in the variable content, then those'll still result in copies!

So this is good:
<xsl:variable name="baz" select="//bazElem">

As is:
<xsl:variable name="baz" as="node()">
  <xsl:sequence select="//bazElem"/>
</xsl:variable>

But this is going to create a new node in any case:
<xsl:variable name="baz" as="node()">
  <bazElem/>
</xsl:variable>

And any nodes here will also be copies:
<xsl:variable name="baz" as="node()">
  <xsl:copy-of select="//bazElem"/>
</xsl:variable>

Pro-tip: if you're unsure about the type of your variable, just specify "item()*". That'll allow any sort of sequence.

And that's all you need to know to get rid of most of those unnecessary copies. :-)

32 comments:

Anonymous said...

Amiable brief and this mail helped me alot in my college assignement. Gratefulness you seeking your information.

Anonymous said...

Something at me personal messages do not send, a mistake what that

Anonymous said...

Hey, I can't view your site properly within Opera, I actually hope you look into fixing this.

Anonymous said...

My partner and I really enjoyed reading this blog post, I was just itching to know do you trade featured posts? I am always trying to find someone to make trades with and merely thought I would ask.

Anonymous said...

Está tudo, vi a tua pagina e refecti muito,estou ver que estás a trabalhar bem!
Continua com o bom tema!
Cumps

Anonymous said...

A friend in need is a friend indeed

Anonymous said...

Ola gostavas ganhar dinheiro na internet?, então vai http://www.ganhardinheiroonlinefacil.blogspot.com/ com vários modos para ganhar dinheiro na net sem ter de por nada.........

Gurudutt Mallapur said...
This comment has been removed by the author.
Gurudutt Mallapur said...

I'm new to xslt myself but this is what I found on sequence vs copy-of from "xslt by example" tutorial: http://www.xmlplease.com/xmltraining/xslt-by-example/examples/sequence_1.html
========================================
<xsl:variable name="A"><xsl:sequence select="document($path)" /></xsl:variable>
<xsl:variable name="B"><xsl:sequence select="$A [ not(@name='A') ]" /></xsl:variable>
<xsl:variable name="C"><xsl:sequence select="$B[ not(@name='B') ]" /></xsl:variable>

<!-- Works for sequence but returns empty node-set for copy-of -->
<xsl:message><xsl:value-of select="exsl:node-set($C)/*[@name='A']" /></xsl:message>
========================================
xsl:sequence uses references instead of copies. This saves copying time and memory.
But it has a downside. You shouldn't use it in successive filtering of nodes.
Since you can still access the "filtered" branches/nodes with xpaths as above.

Anonymous said...

[url=http://buycialispremiumpharmacy.com/#iclwr]buy cialis[/url] - buy cialis online , http://buycialispremiumpharmacy.com/#zzzol cialis online

Anonymous said...

[url=http://buyviagrapremiumpharmacy.com/#mxlnx]buy cheap viagra[/url] - generic viagra , http://buyviagrapremiumpharmacy.com/#jhewz buy viagra

Anonymous said...

[url=http://viagraboutiqueone.com/#gwfay]viagra 25 mg[/url] - viagra 120 mg , http://viagraboutiqueone.com/#wuxds viagra 120 mg

Anonymous said...

[url=http://buyonlineaccutanenow.com/#mdlim]cheap accutane[/url] - accutane 10 mg , http://buyonlineaccutanenow.com/#ywfnb accutane without prescription

Anonymous said...

Hi, accutane online - generic accutane online http://www.twincitiescheap.com/, [url=http://www.twincitiescheap.com/]buy generic accutane [/url]

Anonymous said...

You finally found the best spot to compare and purchase Invicta Grand Diver [url=http://invicta-grand-diver.pkak.com/] Invicta Grand DiverWatches.[/url]
In our site you can compare the prices from high quality shops.
You can find full details and description of our Invicta Grand Diver Watches.
Here you'll be able to buy the right [url=http://invicta-grand-diver.pkak.com/] Invicta Grand Diver watches[/url] that fits your needs and budget, and most important, those you wish to have.

OBAT FLEK PARU PARU said...

Silahkan kunjungi :
http://arkanherbal.com/obat-trikomoniasis/
http://arkanherbal.com/cara-mengobati-abses-payudara/
http://qncjellygamat.org/obat-patah-tulang-pergelangan-tangan/
http://qncjellygamat.org/obat-patah-tulang-paha/
http://obatparuparubasah.utamakansehat.com/
http://obatkatarak.utamakansehat.com/
http://obatamandel.utamakansehat.com/
http://obatkelenjartiroid.utamakansehat.com/
http://obatflekparuparu.utamakansehat.com/
http://arkanherbal.com/eye-care-softgel/

Unknown said...

cheap oakley sunglasses cheap ray bans Ray Ban Wayfarer ray ban sunglasses for women oakley sunglasses outlet ray ban sunglasses outlet Nike Air Max Cheap Nike Air Max jordans 2016 Nike Store cheap nike basketball shoes lebron james shoes 2016 louboutin shoes red bottoms shoes cheap louboutin shoes christian louboutin store mizuno prophecy mizuno wave fitflop sale mbt shoes for men cheap mbt shoes mizuno shoes fitflops sandals fitflop outlet

Unknown said...

7.12lllllyuan"oakley sunglasses wholesale"
"louis vuitton handbags outlet"
"ray-ban sunglasses"
"michael kors wallet"
"ray ban sunglasses"
"oakley sunglasses wholesale"
"longchamp handbags"
"juicy couture tracksuit"
"prada sunglasses for women"
"swarovski outlet"
"ralph lauren polo"
"longchamp outlet online"
"links of london"
"cartier watches"
"nike roshe run"
"asics"
"ferragamo outlet"
"cheap ray ban sunglasses"
"polo ralph lauren"
"michael kors outlet"
"nike tn pas cher"
"ray ban sunglasses"
"tiffany and co"
"tory burch outlet online"
"michael kors outlet"
"mulberry outlet"
"tiffany jewellery"
"tory burch outlet"
"babyliss pro"
"police sunglasses for men"
"prada outlet online"
"soccer jerseys"
"michael kors clearance"
"mcm outlet"
"true religion jeans outlet"
7.12

Unknown said...

michael kors handbags here
nike outlet is
nike tn link
polo ralph lauren with
cheap mlb jerseys I
nike trainers uk top
cowboys jerseys to
patriots jerseys for
cheap michael kors handbags business
kobe 9 go

Unknown said...

cleveland browns jerseys
browns jerseys
michael kors handbags
michael kors handbags wholesale
under armour outlet
michael kors handbags
broncos jerseys
basketball shoes
pandora jewelry
fitflops shoes

John said...

longchamp bags
christian louboutin shoes
discount oakley sunglasses
louboutin outlet
cheap air max
ralph lauren
true religion outlet online
michael kors outlet canada
longchamp handbags
yeezy boost
20170703yuanyuan

Unknown said...

2017106 leilei3915

ugg boots
cheap jerseys
kate spade handbags
michael kors outlet online
michael kors handbags clearance
ralph lauren shirts
coach outlet online
prada outlet
coach outlet online
fred perry polo

Pengobatan Herbal Penyakit Liver said...

Thanks for sharing the information

Cara Mengobati Asam Lambung
Obat Atasi Alergi Dingin
Khasiat QnC Jelly Gamat
Obat Eksim Atopik
Obat Paling Mujarab Diabetes Melitus
Obat Batu Empedu Alami

Unknown said...

yeezy 700
michael kors handbags
true religion jeans
cheap nfl jerseys
golden goose francy
adidas yeezy
yeezy shoes
yeezy boost 350
kayno
fitflops sale clearance

Unknown said...

yeezy 700
michael kors handbags
true religion jeans
cheap nfl jerseys
golden goose francy
adidas yeezy
yeezy shoes
yeezy boost 350
kayno
fitflops sale clearance

Unknown said...

yeezy 700
michael kors handbags
true religion jeans
cheap nfl jerseys
golden goose francy
adidas yeezy
yeezy shoes
yeezy boost 350
kayno
fitflops sale clearance

love said...

zzzzz2018.7.24
canada goose jackets
nike factory store
dsquared
nhl jerseys
christian louboutin shoes
ralph lauren outlet
pandora
ray ban sunglasses
nike blazer pas cher
louboutin shoes

jeje said...

Timothy Olyphant est toujours asics maillot équipe de france athlétisme au chapeau de cowboy ce que Michael Jordan est aux baskets Nike. Commencez à vous prendre plus au sérieux. Le Colibri Evoke est groupe asics france un briquet à flamme unique fabriqué en pensant au style et à la classe. Le baskets asics gel nimbus femme Nike Air Max Classic BW est essentiellement le premier Nike Air Max LTD hommes, renommé seulement. Nike nike pas cher bangkok Shox Deliver joue le même jeu et va se battre. L'extrémité moyenne et supérieure est dominée par les Nike Air Max 97 Chaussures deux autres types.

zzyytt said...

air max
adidas nmd
nike cortez
yeezy shoes
adidas yeezy
adidas shoes
air force 1
jordan shoes
curry 5
golden goose

chenlili said...

ugg outlet
mbt shoes
coach outlet
michael kors outlet
michael kors outlet
lacoste outlet
coach outlet online
michael kors outlet
yeezy boost 350
polo ralph lauren
yaoxuemei20181105

zzyytt said...

converse outlet store
nike air max 2018
air jordans
red bottom shoes
supreme hoodie
nike roshe run
yeezy boost 350 v2
balenciaga shoes
mlb jerseys
nike kd 11

zzyytt said...

converse outlet store
nike air max 2018
air jordans
red bottom shoes
supreme hoodie
nike roshe run
yeezy boost 350 v2
balenciaga shoes
mlb jerseys
nike kd 11