Fela Maslen
Fela Maslen

Reputation: 2172

How expensive are power operations in Javascript?

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?

Upvotes: 0

Views: 237

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1075249

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.

Upvotes: 4

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276496

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.

Upvotes: 2

Related Questions