【发布时间】:2015-12-11 20:10:54
【问题描述】:
我注意到各种对象实例化方法之间存在显着的性能差异。此外,似乎对象的大小(即属性的数量)有时非常重要。
任何人都可以阐明以下 jsperf 的结果吗? http://jsperf.com/objects-w-more-less-8-properties/5
var thisobj = {a:1,b:2,c:3,d:4,e:5,f:6,g:7,h:8}
这似乎是创建新对象的绝食方法
var thisobj = {a:1,b:2,c:3,d:4,e:5,f:6,g:7,h:8,i:9}
这要慢得多......唯一的区别是第 9 个值
var thisobj = new objsm(1,2,3,4,5,6,7,8);
与
var thisobj = new objlg(1,2,3,4,5,6,7,8,9);
彼此之间没有太大区别(大约与您期望的一样多),但它们与上面“动态”定义的对象仍有很大不同。它们的对象在这里定义:
var objsm = function (a,b,c,d,e,f,g,h) {
this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; this.f = f; this.g = g; this.h = h;}
var objlg = function (a,b,c,d,e,f,g,h,i) {
this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; this.f = f; this.g = g; this.h = h; this.i = i; }
为什么“var thisobj = {a:1,b:2,c:3,d:4,e:5,f:6,g:7,h:8}”如此优越?
【问题讨论】:
-
fyi,在 Chrome 中,差异更加夸张。
-
在 Firefox 42 上差异很小
-
可能和JIT进来的时候有关
-
我认为这与缓存有关。
标签: javascript performance object instantiation microbenchmark