getstyle性能比較
var Element = {};
Element.getStyles1 = function() {
var view = document.defaultView;
var propCache = {};
var camelRe = /(-[a-z])/gi;
var camelFn = function(m, a) {
return a.charAt(1).toUpperCase();
};
return view && view.getComputedStyle ? function(el, prop) {
var v, cs, camel;
if (prop == 'float') {
prop = "cssFloat";
}
if (v = el.style[prop]) {
return v;
}
if (cs = view.getComputedStyle(el, "")) {
//if (!(camel = propCache[prop])) {
//camel = propCache[prop] = prop.replace(camelRe, camelFn);
// }
camel = prop.replace(camelRe, camelFn);
return cs[camel];
}
return null;
} : function(el, prop) {
var v, cs, camel;
if (prop == 'opacity') {
if (typeof el.style.filter == 'string') {
var m = el.style.filter.match(/alpha\(opacity=(.*)\)/i);
if (m) {
var fv = parseFloat(m[1]);
if (!isNaN(fv)) {
return fv ? fv / 100 : 0;
}
}
}
return 1;
} else if (prop == 'float') {
prop = "styleFloat";
}
if (!(camel = propCache[prop])) {
camel = propCache[prop] = prop.replace(camelRe, camelFn);
}
if (v = el.style[camel]) {
return v;
}
if (cs = el.currentStyle) {
return cs[camel];
}
return null;
};
}();
Element.getStyles2 = function(element, style) {
var camelRe = /(-[a-z])/gi;
var propCache = {};
var camelFn = function(m, a) {
return a.charAt(1).toUpperCase();
};
//if (!(camel = propCache[style])) {
camel = propCache[style] = style.replace(camelRe, camelFn);
// }
style = style == 'float' ? 'cssFloat' : camel;//style.replace(camelRe, camelFn);;
var value = element.style[style];
if (!value || value == 'auto') {
if(document.defaultView)
var css = document.defaultView.getComputedStyle(element, null);
value = css ? css[style] : null;
}
if (style == 'opacity')
return value ? parseFloat(value) : 1.0;
return value == 'auto' ? null : value;
};
var s = ['width', 'heigth', 'opacity', 'float', 'margin', 'border',
'background', 'top', 'button','padding-left','padding-right','margin-bottom','border-bottom-width','border-right-width'];
var now = new Date().getTime();
for (var i = 0;i < 10000; i++) {
var m =parseInt(Math.random()*(s.length-1))+1;
var el=document.getElementById('test1');
Element.getStyles1(el, s[m]);
}
var now1 = new Date().getTime();
alert(now1 - now);
var now = new Date().getTime();
for (var i = 0;i < 10000; i++) {
var m =parseInt(Math.random()*(s.length-1))+1;
Element.getStyles2 (document.getElementById('test1'), s[m]);
}
var now1 = new Date().getTime();
alert(now1 - now);
Extを分析して、ext、yui(style 1のような実装)がそうするかどうかを感じて、性能のテストをしました.
IEでstyle 1:420-440間、style 2:'453-470間
FFではstyle 1:953-970間、style 2:1266-1287間
cameキャッシュを加えたパフォーマンスは0-20に向上しました.
prototypeはもちろん、mootoolsのようなgetstyle 2の実装に問題があります.しかも性能がかなり悪く、5分の1遅い.