jljlpch 发表于 2013-1-29 07:40:48

getstyle性能比较

var Element = {};Element.getStyles1 = function() {var view = document.defaultView;var propCache = {};var camelRe = /(-)/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) {return v;}if (cs = view.getComputedStyle(el, "")) {//if (!(camel = propCache)) {//camel = propCache = prop.replace(camelRe, camelFn);//}camel = prop.replace(camelRe, camelFn);return cs;}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);if (!isNaN(fv)) {return fv ? fv / 100 : 0;}}}return 1;} else if (prop == 'float') {prop = "styleFloat";}if (!(camel = propCache)) {camel = propCache = prop.replace(camelRe, camelFn);}if (v = el.style) {return v;}if (cs = el.currentStyle) {return cs;}return null;};}();Element.getStyles2= function(element, style) {var camelRe = /(-)/gi;var propCache = {};var camelFn = function(m, a) {return a.charAt(1).toUpperCase();};//if (!(camel = propCache)) {camel = propCache = style.replace(camelRe, camelFn);//}style = style == 'float' ? 'cssFloat' : camel;//style.replace(camelRe, camelFn);;var value = element.style;if (!value || value == 'auto') {if(document.defaultView)var css = document.defaultView.getComputedStyle(element, null);value = css ? css : 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);}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);}var now1 = new Date().getTime();alert(now1 - now); 在分析Ext,觉得ext,yui(类似style1的实现)要不要这样做,于是做了一个性能的测试
在IE中 style1:420-440之间,style2:'453-470之间
在FF中,style1:953-970之间,style2:1266-1287之间
加上came缓存的性能提升在0-20之间。
 
先不用去说prototype,mootools的类似的getstyle2的实现上有点问题。而且性能还是差很多,要慢五分之一。
页: [1]
查看完整版本: getstyle性能比较