Skip to content

Instantly share code, notes, and snippets.

@Integralist
Last active May 31, 2025 20:16
Show Gist options
  • Save Integralist/1247263 to your computer and use it in GitHub Desktop.
Save Integralist/1247263 to your computer and use it in GitHub Desktop.
Create Elements using memoization technique (modified to @GarrettS' points) #js
/**
* 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);
}
}())
@GarrettS
Copy link

GarrettS commented Oct 4, 2011

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