Javascript chaining methods and processing time

十年热恋 提交于 2020-01-21 13:56:13

问题


I was working with a javascript API and I saw this quote:

Because JavaScript is a scripting language, every line of code takes up valuable processor time. One way to improve processor time is to chain method calls to reduce lines of code. Objects such as esri.Graphic and esri.symbol.* provide setter methods that return the object itself, allowing for chaining of methods.

Less efficient:

var symbol = new esri.symbol.SimpleMarkerSymbol();
symbol.setSize(10);
symbol.setColor(new dojo.Color([255,0,0]));

More efficient:

var symbol = new esri.symbol.SimpleMarkerSymbol().setSize(10).setColor(new dojo.Color([255,0,0]));

When chaining method calls, you need to determine a balance between efficiency and readability of your code. Your code might be more readable and maintainable if you avoid chaining; however, you will forfeit the performance benefit that chaining offers.

I understand in Java, writing a chain method vs the stack of methods should compile down to the same bytecode. However, since this is a scripting language, does this really hold water? Also, if it does, is it worth sacrificing the readability for the code for the performance of that section of code?

And for reference on where I got this text from: http://help.arcgis.com/en/webapi/javascript/arcgis/jshelp/inside_graphics.html

Edit: After some performance testing, I have found that it doesn't really matter whether or not the methods are chained or not. (One time one would be faster, another time the other was faster)


回答1:


Chaining methods like this CAN improve performance, but only in limited scenarios where the API you're using is built to provide this functionality. The first example that comes to mind is with jQuery.

Calling $("#test") takes time to return the jquery object that references #test.

When you chain a method, it reuses that object.

Check out this test I made as an example.

http://jsperf.com/chaining-demo



来源:https://stackoverflow.com/questions/15572718/javascript-chaining-methods-and-processing-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!