K2x*_*2xL 6 javascript prototype
所以我写了这些测试,看看使用原型会有多快...
function User() {
return {
name: "Dave",
setName: function(n) {
this.name = n;
},
getName: function() {
return this.name;
}
};
}
function UserPrototype() {
if (!(this instanceof UserPrototype)) return new UserPrototype();
this.name = "Dave";
}
UserPrototype.prototype.getName = function() {
return this.name;
};
UserPrototype.prototype.setName = function(n) {
this.name = n;
};
function setName(obj,name)
{
obj.name = name;
}
function getName(obj)
{
return obj.name;
}
//Test 1
var c = 10000000;
var tstart = 0;
var tend = 0;
tstart = new Date().getTime();
for (var j = 0; j < c; j++) {
var newUser = User();
newUser.setName("michael");
newUser.getName();
}
tend = new Date().getTime() - tstart;
console.log("Returning object with methods: " + tend / 1000.0 + " seconds");
//Test 2
tstart = new Date().getTime();
for (var j = 0; j < c; j++) {
var newUser = new UserPrototype();
newUser.setName("michael");
newUser.getName();
}
tend = new Date().getTime() - tstart;
console.log("Using prototypes: " + tend / 1000.0 + " seconds");
//Test 3
tstart = new Date().getTime();
for (var j = 0; j < c; j++) {
var newUser = {name:"dave"};
setName(newUser,"michael");
getName(newUser);
}
tend = new Date().getTime() - tstart;
console.log("Using general functions: " + tend / 1000.0 + " seconds");
?
Run Code Online (Sandbox Code Playgroud)
我的结果:
Returning object with methods: 9.075 seconds
Using prototypes: 0.149 seconds
Using general functions: 0.099 seconds
Run Code Online (Sandbox Code Playgroud)
我写了前两个测试,当我看到结果时,我想到了为什么我看到它们......我在想,原因是返回的对象很慢,因为每次都会创建两个新的方法属性实例在原型方法更快的情况下实例化对象,因为它只创建一次函数.一般函数调用和原型之间的性能接近让我觉得我的假设是正确的.
所以我的第一个问题是,我对我的假设是对的吗?
我的第二个问题是,如何使原型的写作更具可读性,同时保持高性能?有没有办法以一种看起来像是在"类"中的方式对原型进行编码(如果这样做有意义的话)
*编辑 - 我忘了用Object.create()做测试,只做了一个并发布了结果.JSFiddle:(http://jsfiddle.net/k2xl/SLVLx/).
我现在得到:
Returning object with methods: 0.135 seconds fiddle.jshell.net:63
Using prototypes: 0.003 seconds fiddle.jshell.net:72
Using general functions: 0.002 seconds fiddle.jshell.net:81
Returning object.create version: 0.024 seconds
Run Code Online (Sandbox Code Playgroud)
看起来这可能是解决方案?
我同意你的假设。如果代码这样写的话,这也是可以的:
function UserObject() {
this.name = "Dave";
this.getName = function() {
return this.name;
};
this.setName = function(n) {
this.name = n;
};
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,就像在“对象”方法中一样,每次构造对象时都会创建getName和方法。setNameUserObject
“原型”和“函数”方法之间的代码存在细微差别。删除if (!(this instanceof UserPrototype)) return new UserPrototype();(这是不必要的安全防护措施)可以减少很多。也可以说,更接近的比较......
var newUser = new UserPrototype();
[newUser].name = "Dave";
Run Code Online (Sandbox Code Playgroud)
... 是 ...
var newUser = new Object();
newUser.name = "dave";
Run Code Online (Sandbox Code Playgroud)
... 因为 ...
var newUser = {name:"dave"};
Run Code Online (Sandbox Code Playgroud)
Object...在创建和添加属性时高度依赖本机代码name。
在这种情况下,结果会翻转,“原型”方法会更快出现。在这里查看 jsFiddle:
关于如何使你的原型更具可读性,我无能为力。对我来说,它们是可读的:-)
| 归档时间: |
|
| 查看次数: |
1008 次 |
| 最近记录: |