Javascript链接方法和处理时间 [英] Javascript chaining methods and processing time

查看:86
本文介绍了Javascript链接方法和处理时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用javascript API,我看到了这句话:

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


因为JavaScript是一种脚本语言,所以每一行代码都需要宝贵的处理器时间。改善处理器时间的一种方法是链式方法调用以减少代码行。诸如esri.Graphic和esri.symbol。*之类的对象提供了返回对象本身的setter方法,允许链接方法。

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.

效率低下:



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.

我在Java中理解,编写链方法与方法堆栈应该编译成相同的字节码。但是,由于这是一种脚本语言,这真的有用吗?此外,如果确实如此,是否值得牺牲代码的可读性来执行该部分代码?

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?

以及我从何处获得此文本的参考: http://help.arcgis.com/en/webapi/javascript /arcgis/jshelp/inside_graphics.html

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

编辑:经过一些性能测试后,我发现方法是否真的无关紧要链式与否。 (一次更快,另一次更快)

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)

推荐答案

像这样的链接方法可以提高性能,但仅限于在有限的情况下,您正在使用的API是为了提供此功能而构建的。想到的第一个例子是jQuery。

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.

调用$(#test)需要时间来返回引用#test的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

这篇关于Javascript链接方法和处理时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆