Cloning CSSStyleDeclaration from getComputedStyle (v5)

Revision 5 of this benchmark created on


Description

I need to store a copy of CSSStyleDeclaration.

There are two way to clone it:

  1. by enumerating non-digit attributes using for-in
  2. by splitting CSSText string
  3. by enumerating digit attributes

Setup

window.computed = window.getComputedStyle(document.body);
    window.clonedTarget = {};

Teardown


    var c=0, err=[];
    for(var attr in clonedTarget){
      if(clonedTarget.hasOwnProperty(attr) && (clonedTarget[attr] != computed[attr])){
        err.push('ERROR: ' + attr + ': '+ clonedTarget[attr] + '!=' + computed[attr]);
      };
      c++;
    }
    if(c!=computed.length){
        err.push('ERROR: different lengths ' + c +  ' != ' + computed.length);
    }
    if(err.length){
      throw err;
    }
  

Test runner

Ready to run.

Testing in
TestOps/sec
Enumerate all non-numeric attributes
var attr;

for(attr in computed){
  if(computed.hasOwnProperty(attr) && isNaN(+attr) &&
     attr !== 'cssText' && attr !== 'length' && attr !== 'parentRule'){
    clonedTarget[attr] = computed[attr];
  }
}
ready
Splitting cssText results
computed.cssText.split(';').slice(0, -1).forEach(function(declaration){
  var colonPos = declaration.indexOf(':');
  var attr = declaration.slice(0, colonPos).trim();

  clonedTarget[attr] = declaration.slice(colonPos+2);
});
ready
by enumerating digit attributes
var i, attr;

for(i=0; attr=computed[i++];){
  clonedTarget[attr] = computed[attr];
}
ready
by enumerating digit attributes (as an array)
var i, attr, arr;

arr = Array.prototype.slice.call(computed);

for(i=0; i<arr.length; i+=1){
  attr = arr[i];
  clonedTarget[attr] = computed[attr];
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.