java-script对象减速结构在维护,性能和内存方面都很好?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (42)

我的对象结构类似于下面的形式,我可以用3种方式编写:

1.在所有地方使用完全限定名称。

context.flow.myobject = {}; context.flow.myobject.SomeValue = 11; context.flow.myobject.IsNumber = function(){ //Check if it is a number. }; context.flow.myobject.Calculate = function(value){ if(context.flow.myobject.IsNumber()){ // Preform calculations. // Will use this variable at multiple place in // this function as **context.flow.myobject.SomeValue** } };

2.使用内联和此关键字:

context.flow.myobject = { SomeValue: 11, IsNumber: function(){ //Check if it is a number. }, Calculate: function(value){ if(this.IsNumber()){ // Preform calculations. // Will use this variable at multiple place in // this function **this.SomeValue** } } };

3.使用引用的对象:

context.flow.myobject = {}; context.flow.myobject.SomeValue = 11; var myobject = context.flow.myobject; myobject.IsNumber = function(){ //Check if it is a number. }; myobject.Calculate = function(value){ if(context.page.main.MY_VAR.IsNumber()){ // Preform calculations. // Will use this variable at multiple place in // this function **myobject.SomeValue** } };

4.或者我可以使用类似于第二种方法的构造函数:

context.flow.myobject = function(){ this.SomeValue = 11; this.IsNumber: function() { //Check if it is a number. }; this.Calculate: function(value) { if(this.IsNumber()) { // Preform calculations. // Will use this variable at multiple place in // this function **this.SomeValue** } } };

提问于
用户回答回答于

可以通过将something.far.away作为快捷方式(本地化)来增加性能:

function foo(){ var farAway = something.far.away; // do many things with farAway; }

是将far.away.things本地化。例如:

something.far.away = 42; function foo(x, y){ var far = something.far.away; // localize var ret = 0; for(var i=0; i< 1000000; i++){ ret += far + x - far / y; } return ret; }

如果只使用一次,则性能不会提高:

function nope(x, y){ // NO performance increase, this is actually less performant // because we have to store a new var, then go retrieve it! var far = something.far.away; return far + x + y; }

可以本地化功能,所以在你的例子中,可能将#3清理为:

// objects are "by reference", see link after code block. context.flow.myobject = {}; var obj = context.flow.myobject; // localize obj.SomeValue = 11; obj.IsNumber = function(value) { //Check if it is a number. } obj.Calculate = function(value) { if(obj.IsNumber(value)) { var val = obj.SomeValue; // localize // Preform calculations. // Will use this variable at multiple place in // this function **myobject.SomeValue** } }

扫码关注云+社区

领取腾讯云代金券