Skip to content

Instantly share code, notes, and snippets.

@Integralist
Created September 28, 2011 07:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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)
/**
* 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

What triggers the error in IE?

Could be reduced to:

createElement: function(tagname) {
  this.memory = this.memory || {};
  if (!(tagname in this.memory)) {
    this.memory[tagname] = document.createElement(tagname);
  }
 // There's no subtree to clone here.
  return this.memory[tagname].cloneNode(false);
}

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.

createElement: function() {
 var memory = {};
  return function(tagname) {
    if (!(tagname in memory)) {
      memory[tagname] = document.createElement(tagname);
    }
    return memory[tagname].cloneNode(false);
  }
}()

But again, there is a JScript object pointing to a DOM object.

@GarrettS
Copy link

GarrettS commented Oct 4, 2011

And to be fair, there really is no need for this function as it exists. Use document.createElement instead of yourlib.createElement.

@Integralist
Copy link
Author

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

@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