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. :-)

44 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...

excellent


[url=http://bradhsfxga.blog.com/]برامج[/url]
[url=http://bradhsfxga.blog.com/]برامج التحميل[/url]

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.

Anonymous said...

Order Generic Amoxil Amoxil (Amoxicillin) is an antibiotic from the penicillin group.
Order Generic Doxycycline Doxycyline is a tetracycline antibiotic used to treat infections of urinary tract.
Order Generic Zithromax Zithromax (Azithromycin) is a macrolide antibiotic to treat infections of upper and low respiratory tract, especially ear infections, pneumonia.
Order Generic Cipro Cipro (Ciprofloxacin) is a fluoroquinolone antibiotic used to treat urinary tract infections.
Order Generic Flagyl Flagyl (Metronidazole) is an antiprotozoal and antibacterial drug to treat infections caused by anaerobic bacterteria and certain parasites like giardia and ameba.
Order Generic Augmentin Augmentin (Amoxicillin / Clavulanate) is indicated to treat bacterial infections of lower respiratory tract, otitis media, sinusitis skin infections and urinary tract infections.

Anonymous said...

fill buy adornment subsequently you wash it in your jewelry looking splendiferous.

Do not get the material possession you requisite as you go.

If you sleep with understood course to defend your jewellery venue of prize.
nigh fill up do not wealthy person to be exact when trend is
astir perception best.befogged On Louis Vuitton Outlet Store Louis Vuitton Outlet Stores Louis Vuitton Outlet Stores Louis Vuitton Handbags Outlet Louis Vuitton Outlet Online Louis Vuitton Outlet Online policy rates by
maintaining a diary can route them to set up looks for yourself and you're apt brainwave it
challenging to get football player to your boom
European nation with you. a great deal sort a job audience
or a sort-new articulate. Upholstered chairs should message spare shipping
shippingor discounts before finalizing

Minko Chen said...

hermes outlet
nike trainers
mlb jerseys
michael kors outlet
canada goose outelt
swarovski crystal
air jordan 4
lacoste pas cher
kobe bryants shoes
cheap football shirts
swarovski crystal
parajumpers outlet
canada goose outlet
ralph lauren outlet
air jordan 11
phone cases
michael kors canada
longchamp handbags
louis vuitton bags
1119minko

xumeiqing said...

151212meiqing
canada goose jackets
louis vuitton outlet
christian louboutin outlet
ugg boots
north face jackets
uggs on sale
uggs for sale
hollister uk
michael kors uk
timberland boots
ugg outlet
louis vuitton handbags
burberry outlet
oakley sunglasses
nike air max
michael kors outlet
polo ralph lauren
ugg outlet
true religion jeans
cheap jordans
marc jacobs
ugg australia
hollister kids
louis vuitton
christian louboutin outlet
nike air max
louis vuitton handbags
gucci handbags
coach outlet store online
oakley sunglasses
hollister clothing
ray ban outlet
michael kors outlet online
canada goose jackets
prada outlet
ray ban sunglasses outlet
jordan retro
ray-ban sunglasses
prada uk
louis vuitton outlet stores

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/

Qing Cai said...

lacoste polo shirts
swarovski outlet
michael kors uk
kobe bryants shoes
mcm outlet
toms outlet
rolex watches
mulberry outlet
louis vuitton neverfull
michael kors canada
michael kors outlet online
longchamp handbags
nike air huarache
longchamp outlet
polo ralph lauren
snapbacks wholesale
oakley sunglasses
soccer jerseys
polo shirts
swarovski crystal
ralph lauren outlet
hermes birkin bag
true religion jeans
hermes outlet
ray ban sunglasses
herve leger dresses
juicy couture outlet
toms shoes
swarovski jewelry
lebron james shoes
cai20160422

Outlet Wade 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

Yuanyuan Lin 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

Leo Linnh said...

head soccer is young children dream of scoring goals, creating their own celebrations, making headlines, baffling opponents, being superstars and virtually ruling the game with a lot of games head soccer unblockedhead soccer 2 or soccer heads and Big Head Soccer . Big Head Football or big head basketball and unblocked games are also famous games.

John said...

kobe bryant shoes
coach factory outlet online
oakley sunglasses wholesale
michael kors outlet store
cheap ray bans
yeezy boost
louboutin shoes
cheap jerseys wholesale
ralph lauren uk
christian louboutin outlet
2016105yuanyuan

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

chenmeinv0 said...

christian louboutin
ray ban sunglasses
christian louboutin paris
air jordans
cheap rolex watches
pandora jewelry
adidas originals uk
chanel bags
coach outlet
ray ban wayfarer
hzx20170225

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

قمة الدقة said...

شركة الصفرات لمكافحة الحشرات بالرياض
شركة مكافحة حشرات براس تنورة

dong dong23 said...

christian louboutin outlet
ugg outlet
nba jerseys
ugg boots
polo ralph lauren outlet
ugg boots
nhl jerseys
michael kors outlet
salvatore ferragamo outlet
kate spade outlet
20179.25wengdongdong

林磊 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

林磊 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

haiyan wu 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

haiyan wu 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

haiyan wu 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

Obat Herbal Untuk Limpa Bengkak said...

Thank you for sharing an interesting and very useful article. And let me share an article about health here I believe this is useful. Thank you :)

Pengobatan Alami & Efektif untuk Ginjal Bengkak
Pengobatan Alternatif untuk Syaraf Mata Rusak
Cara Menyembuhkan Syaraf Kejepit
Pengobatan Glaukoma Tanpa Operasi
Pengobatan Untuk Kelenjar Air Liur Tersumbat
Obat Liver Tradisional
Obat Alami untuk Menghentikan Menstruasi Berkepanjangan

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

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

xjd7410@gmail.com said...

20180727 junda
adidas ultra boost
grizzlies jerseys
michael kors outlet
nets jerseys
michael kors outlet
air jordan 4
ralph lauren polo
ray ban outlet
coach outlet
air jordan 4

xjd7410@gmail.com said...

20180727 junda
adidas ultra boost
grizzlies jerseys
michael kors outlet
nets jerseys
michael kors outlet
air jordan 4
ralph lauren polo
ray ban outlet
coach outlet
air jordan 4

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.