Reputation: 1695
I am in a position to compare a string with an integer in my application. So I have a choice of either converting my variable of string type to integer or vice-versa and then compare. In this case I would like to know which process is faster, is converting a string to integer or integer to string or can I use "==" and compare them.
Upvotes: 1
Views: 163
Reputation: 19423
I think integer to string conversion is faster because every integer can be converted to a string, but the reverse conversion is not always possible, i.e. not every string represents a number.
==
performs automatic conversion of its operands and then performs comparison, so you can use it with two operands of any type.
In the case of string and number, ==
first tries to convert the string into a number and then performs the comparison, perhaps and I am assuming this, it tries to convert the string to a number because if that fails no need for comparison altogether.
EDIT: I have run a few tests using parseInt()
for string to integer conversion, and using toString()
for integer to string conversion.
Each test was run 1000000
times, the string to integer conversion took about 3
seconds in average, the integer to string conversion took about 2.5
seconds in average.
This is not a huge difference for 1000000
operations, so unless you have a huge number of conversions to do, it won't make any difference.
Upvotes: 2
Reputation: 1068
JavaScript is not a strictly typed language. Any var
can be a string
, int
, double
, bool
etc.
There shouldn't be any speed difference for comparisons of two vars
.
You can open statistic in browsers in their developer tools to see the speed of loading objects such as scripts and test for yourself if there are any differences in speed.
In Chrome, it is the Network
tab.
Upvotes: 0