How fast is parseFloat Vs. float ints in JavaScript?
I'm getting a huge dataset from a client's internal API. It'll contain a bunch of numerical data of prices such as: $31.23. He gives them to me as {"spend":"21.23"}
which is fine, but I was concerned that after 1000+ items and running parseFloat()
on all of those values (on top of graphing them) might be resource heavy on the client's browser.
Has anyone done this?
==Update==
I'm sorry. My question was too vague. My concern was that it's a string and i'm parsing it. My issue was is pars开发者_开发问答eFloat faster than just an int. I.e. is appending parseFloat("12.12")
to a div faster than simply just appending 12.12
and if so, how much faster.
On my work machine (Mac OS X, Intel 2 GHz Core i7), I saw the following results on jsperf.com:
Browser | parseFloat calls per second
----------------------------------------
Chrome 12 | 5.3 million
Firefox 6 | 21.7 million
IE 8 | 666.9 thousand <- totally unfair, ran on virtual machine
Opera 11 | 5.2 million
This is far from an exhaustive survey; but at a rough minimum of over 600 thousand calls per second (and that on a virtual machine), I think you should be good.
In regard for speed of parseFloat or parseInt MDN recommends using the unary operator + instead, as in
+"12.12"
=> 12.12
MDN Link
The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already. Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number.
you know that parseFloat()
is based on the browser. So as far as I know the browser could crash after 200 values, could work just fine after 10.000 value.
It depends on how many tabs that browser has, what other scripts is running, how much CPU is free for processing, and of course what browser
if your client uses firefox with 1000 addons it will never run your script smoothly.
just my opinion. If you want to do it nice you should preprocess on a server then display.
Type
javascript:a = +new Date; x = 100000; while (--x) parseFloat("21.23"); alert(+new Date - a);
Into your url bar.
This is the only way to know for sure.
In honesty, you can't answer the question. It depends on the browser, for example, firefox 8 should be faster than 6, and so on.
精彩评论