0

Does it take a lot of CPU cycles to raise 2 to the power of, say, 29? Multiple times each second?

Or is it worth creating a cache of power variables?

Fela Maslen
  • 2,022
  • 3
  • 25
  • 46

2 Answers2

4

Questions about performance in JavaScript don't usually have a single answer, for the simple reason that each engine is different. What's expensive in one engine (say, Microsoft's JScript) is cheap in another (say, Google's V8).

So a two-part answer:

  1. Don't worry about it until/unless you have a real-world performance issue related to power operations. Until then, it's just a waste to spend time on it.

  2. If that happens, profile the performance of alternatives on the engines you intend to support. If this is a browser-based thing you're working on, http://jsperf.com can be useful there, and all modern browsers have development tools, some with pretty decent profilers.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
2

Modern JavaScript run times do this sort of thing fast!

JavaScript can perform (in Google's v8, SpiderMonkey, JavaScriptCode and in IE10) over 44 million 'two to the power of 29' operations in a second.

Here is a perf

Whenever you run into this sort of question you should profile your code.

Community
  • 1
  • 1
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • 2
    I've got to learn to stop treating computers like they're not the blisteringly fast things that they are. – Fela Maslen May 17 '13 at 11:49
  • 2
    @FelaMaslen: Yeah. The phrase "premature optimization" wasn't really popular in 1987, was it? (Well, you may be too young, so I'll just tell you: No, it wasn't.) But *today*... – T.J. Crowder May 17 '13 at 11:51
  • 1
    @T.J.Crowder Good comment, I just checked in the console of Safari, Chrome, IE10 and Firefox (all still do over 44 million, some much more). I've updated my answer, thanks. – Benjamin Gruenbaum May 17 '13 at 11:51