Last active
May 31, 2025 20:16
-
-
Save Integralist/1247263 to your computer and use it in GitHub Desktop.
Create Elements using memoization technique (modified to @GarrettS' points) #js
This file contains hidden or 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); | |
} | |
}()) |
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
And to be fair, there really is no need for this function as it exists. Use
document.createElement
instead ofyourlib.createElement
.