Hi all. Im new to JS and would like to note the following case:

Ive run the following test numerous times


<script type="text/javascript">

var s = 0, o = 0;

for (a=0;a<=10;a++)
	var start = new Date().getTime();

	var res = 0;
	for (b=0;b<=100000000;b++)
		res = 512/128;

	var end = new Date().getTime();
	s += end - start;
	var start1 = new Date().getTime();

	for (c=0;c<=100000000;c++)
		res = 512>>7;

	var end1 = new Date().getTime();
	o += end1 - start1;


and 9 times out of then the shift operation is faster, but never by much (around 5-10%)

My question is this? Does the javascript compiler notice a possible shift operation and if so perform one. If so why the slight performance increase when using a shift operator?

Please note the number (as long as in power of 2's) and the operation (* or /) didnt really make a difference. Shifts were still slightly faster.

Thank you.

Recommended Answers

All 2 Replies


Thoughts, nothing definitive .....

As far as I am aware, browser-based javascript interpreters don't do any optimisation; they simply execute exactly what you wrote in the way you wrote it, warts and all. Other incarnations of javascript, eg NODE, may be different but I have no specific knowledge.

The difference in performance that you have seen may be accounted for (at least in part) by javascript not having an Integer type. All numbers are Float, even a simple 2. I doubt very much that js interpreters have the wherewithal to spot intergeresque variables; therefore (still guessing) all numeric operations are Floaty.

Google's Closure Compiler certainly optimises but from what I have read, it's more concerned with higher level issues and code minimisation than low level concerns like converting 2^n multipliers to shifts. You would need to do some investigation of your own in this regard.


Thanks for the response.

I didn't know that JavaScript treats all numbers as floats. Also thanks for the link to the Closure Compiler. This sounds interesting and worth the time.


Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.