Javascript chaining methods and processing time

2019-02-26 02:41发布

问题:

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