Created
September 28, 2011 07:44
-
-
Save Integralist/1247263 to your computer and use it in GitHub Desktop.
Create Elements using memoization technique (modified to @GarrettS' points)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* The following method creates a new element or returns a copy of an element already created by this script. | |
* | |
* @param tagname { String } element to be created/copied | |
* @return { Element/Node } the newly created element | |
*/ | |
createElement: (function(){ | |
// Memorize previous elements created | |
var cache = {}; | |
return function(tagname) { | |
if (!(tagname in cache)) { | |
// Create new instance of specified element and store it | |
cache[tagname] = document.createElement(tagname); | |
} | |
// If we've already created an element of the specified kind then duplicate it | |
return cache[tagname].cloneNode(false); | |
} | |
}()) |
And to be fair, there really is no need for this function as it exists. Use document.createElement
instead of yourlib.createElement
.
I guess so, but although I'm sure the performance gains are negligible it still feels like if you can cache the results of createElement() then surely it should be worth doing.
But thanks for your help cleaning it up none-the-less! :-)
Shallow cloning one element won't do much.
http://jsperf.com/clonenode-vs-createelement-performance/2
Except for img
elements in Firefox 7, it looks like the benefit could be explained by setting the property again.
The extra function dependency in the codebase must be maintained and downloaded. Just document.createElement
is simpler.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What triggers the error in IE?
Could be reduced to:
There's no subtree to clone, so cloneNode(false). I prefer this for clarity, not for the negligibly slight performance benefit.
Binding a DOM object to a JScript object in IE can easily lead to a circular reference. I usually try to avoid doing that.
If
memory
is used internally, a variable can be used.But again, there is a JScript object pointing to a DOM object.