最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

optimization - How expensive are function calls in JavaScript? - Stack Overflow

programmeradmin2浏览0评论

I've been looking at other people's JavaScript code, and I've noticed that many programmers tend to create functions that could be combined with the functions that are calling them. One example is this; the 'initWebGL' function could be combined with the 'start' function and it'd function the same. Another example is in the source of this, where function 'tick', which is called every 15 milliseconds, makes calls to two other functions that may just as well be combined with 'tick'. I understand the organizational qualities of this, but I am curious about the effect on performance. Is doing this good practice, especially considering that JavaScript is an interpreted language?

I've been looking at other people's JavaScript code, and I've noticed that many programmers tend to create functions that could be combined with the functions that are calling them. One example is this; the 'initWebGL' function could be combined with the 'start' function and it'd function the same. Another example is in the source of this, where function 'tick', which is called every 15 milliseconds, makes calls to two other functions that may just as well be combined with 'tick'. I understand the organizational qualities of this, but I am curious about the effect on performance. Is doing this good practice, especially considering that JavaScript is an interpreted language?

Share Improve this question asked Jan 17, 2010 at 8:25 SkofoSkofo 1432 silver badges7 bronze badges 3
  • 1 Doesn't this depends on which interpreter you use? – kennytm Commented Jan 17, 2010 at 8:35
  • 1 If a programming language requires you to lose organization to be efficient enough, that language should be fired. – seanmonstar Commented Jan 17, 2010 at 9:08
  • 4 Function calls in Javascript are less expensive than the maintenance nightmare caused by poorly-organized code. – friedo Commented Jan 17, 2010 at 9:12
Add a comment  | 

3 Answers 3

Reset to default 9

Best practice for any language is to write code that is readable and maintainable first, and then to optimize if needed.

If your program runs fast enough split into easy-to-digest chunks, then leave it that way. If it's running slowly, then like hobodave mentioned, profile to find the cause of the slowness.

Chances are, it's going to be caused by something other than calling functions, but if it happens to be caused by that, then start combining functions together, once you've tracked it down to that.

http://www.slideshare.net/madrobby/extreme-javascript-performance slides 10..19

10 000 calls makes a difference in IE and Firefox. 1 call don't.

The best way to learn how "expensive function calls are", a completely vague and context specific metric, is to profile it yourself:

  • Download Firefox
  • Download Firebug
  • Profile with firebug
发布评论

评论列表(0)

  1. 暂无评论