Method vs Basic JS? Should I use toString? parseInt? jQuery? - javascript

This is a question I've been wondering about ever since I found the toString() function, but have never bothered to ask. Should I use basic JS or the function that does the same thing?
Now, don't get me wrong, I realize toString has its redeeming qualities, like converting a function to a string.
var message = function() {
// multi
// line
// string
}.toString();
But admit it: we mainly use toString for converting numbers to strings. Couldn't we just do this instead?
var myNumber = 1234;
var message = ''+myNumber;
Not only is this shorter, but according to JSPerf the toString method is 97% slower! (Proof: http://jsperf.com/tostring-vs-basic-js ) And as I said, I know toString is useful, but when people raise question about types of Javascript variables, toString() usually comes up. And this is, like, basic Javascript. Every browser can do quotes.
Same goes for parseInt. Now, before I discovered parseInt, I discovered that multiplying a string by one would convert it to a number. That's because you cannot multiply a string, naturally, forcing Javascript to treat it as a number.
var message = "4321";
var myNumber = message*1;
Now, interestingly, this is slower than parseInt, but not by much. I also noticed that an empty string, or one without numbers, will return 0, whereas parseInt will return NaN because there are no numbers in the string. Once again, I realize parseInt is faster and can convert to different bases. However, multiplying is shorter, will work in any browser, and parseInt, remember, will only return integers. So why does it always come up as the answer to questions, asking how to convert to numbers/what NaN is?
Now this might be going a little bit off topic, but I actually wonder a similar thing about jQuery. Once again, jQuery is something I've never really understood the use for. Javascript code is clean and jQuery is in and of itself a JS file, so it cannot do anything Javascript can't do. It may simplify certain functions and stuff, but why not just copy those functions to your page then and leave out the remaining functions you don't use? It seems overkill to include jQuery merely to complete one simple task. And animation isn't excused either here - because that too can be done with native Javascript. So why jQuery?
Ultimately what I'm asking is, why do we need these things for these purposes when there are better methods? Or are they better methods? Is using functions a better practive just in general?

Not only is this shorter, but according to JSPerf the toString method is 97% slower!
Unless you're calling .toString() on hundreds of millions of numbers every second and you've found that this is a bottleneck in your application through profiling, this should not be a factor at all.
But admit it: we mainly use toString for converting numbers to strings
As you've seen, this can be done implicitly by just adding a string and a number together, so I fail to see any benefit of using '' + n in place of n.toString(). The latter is more readable when you're not actually concatenating n with a string.
However, multiplying is shorter, will work in any browser, and parseInt, remember, will only return integers.
Are you saying that parseInt doesn't work in every browser? If you want to parse something as an integer, use parseInt. If you want to parse something as a float (JavaScript doesn't actually have a special type for either, all numbers are floats), use parseFloat.
The more common pattern is using +'123', which has the exact same behavior as 1 * '123'. parseInt handles empty strings properly, but for whatever reason does not validate strings as you'd expect. The unary plus returns NaN in case of an error, but treats whitespace and empty strings incorrectly. It's one of JavaScript's shortcomings, so there's really no concrete choice between the two if you're working in base 10.
So why does it always come up as the answer to questions, asking how to convert to numbers/what NaN is?
Because the spec included these functions to convert strings into numbers and converting strings into numbers using binary operators like you're doing is a side effect, not the primary purpose. Also you can parse integers in different bases using parseInt, which isn't possible with type coercion.
It may simplify certain functions and stuff, but why not just copy those functions to your page then and leave out the remaining functions you don't use?
If you load jQuery from a CDN, then there's a really good chance that a user's browser has already downloaded it and has it cached, making download times and bloat almost nonexistent. If you make a "custom build", I'd bet that it'll make the site slower on first load.
And animation isn't excused either here - because that too can be done with native Javascript.
So can everything. There's no point in reinventing the wheel every time you write something.

Related

converting LARGE string to an integer [duplicate]

How do I parse a 20-digit number using JavaScript and jQuery?
A 20-digit number is generally too big for a JavaScript native numeric type, so you'll need to find a "big number" package to use. Here's one that I've seen mentioned on Stack Overflow and that looks interesting: http://silentmatt.com/biginteger/
That one is just integers. If you need decimal fractions too, you'll have to find something else.
If you just want to check that a 20-digit string looks like a number, and you don't need to know the value, you can do that with a regular expression.
You can't have a 20-digit number in JavaScript - it'll get floated off on you.
You can keep 20 digits (or 200 or 2000) intact as a string, or as an array of digits, but to do any math on it you need a big integer object or library.
Normally you use Number() or parseInt("", [radix]) to parse a string into a real number.
I am guessing you are asking about what happens when the string you parse is above the int - threshold. In this case it greatly depends on what you are trying to accomplish.
There are some libraries that allow working with big numbers such as https://silentmatt.com/biginteger/ - see answer - (did not test it, but it looks OK). Also try searching for BigInt JavaScript or BigMath.
In short: working with VERY large number or exact decimals is a challenge in every programming language and often requires very specific mathematical libraries (which are less convenient and often a lot slower than when you work in "normal" (int/long) areas) - which obviously is not an issue when you REALLY want those big numbers.

Comma Operator to Semicolons

I have a chunk of javascript that has many comma operators, for example
"i".toString(), "e".toString(), "a".toString();
Is there a way with JavaScript to convert these to semicolons?
"i".toString(); "e".toString(); "a".toString();
This might seem like a cop-out answer... but I'd suggest against trying it. Doing any kind of string manipulation to change it would be virtually impossible. In addition to function definition argument lists, you'd also need to skip text in string literals or regex literals or function calls or array literals or object literals or variable declarations.... maybe even more. Regex can't handle it, turning on and off as you see keywords can't handle it.
If you want to actually convert these, you really have to actually parse the code and figure out which ones are the comma operator. Moreover, there might be some cases where the comma's presence is relevant:
var a = 10, 20;
is not the same as
var a = 10; 20;
for example.
So I really don't think you should try it. But if you do want to, I'd start by searching for a javascript parser (or writing one, it isn't super hard, but it'd probably take the better part of a day and might still be buggy). I'm pretty sure the more advanced minifiers like Google's include a parser, maybe their source will help.
Then, you parse it to find the actual comma expressions. If the return value is used, leave it alone. If not, go ahead and replace them with expression statements, then regenerate the source code string. You could go ahead and format it based on scope indentation at this time too. It might end up looking pretty good. It'll just be a fair chunk of work.
Here's a parser library written in JS: http://esprima.org/ (thanks to #torazaburo for this comment)

'+' or parseInt() - which one is efficient to convert string to integer in javascript

In JavaScript codes, I have seen people using '+' character to convert string to integer as in -
var i = +"2";
another way is just using parseInt() method as following -
var i = parseInt("2");
I want to know which one is efficient?
Sorry I should also add that, I am dealing with integers only and the data is huge so even a little difference in performance would be good for me.
It depends on the Browser.
i've created a nasty little Testcase for some String-To-Number conversion possibilities i know.
Ive also added possibilities to convert to floating-point-numbers, as in Javascript Numbers are Numbers, no matter if they have floating point or not.
Check it out. Corrections and suggestions appreciated!
As some other folks around here said in the comments below the question: I also think its better not to think to much about it, bu to focus on readability..
Long story short, don't worry about it, use whatever is more convinient for you and the actual case; micro-optimizations like this are useless. Id' say just remember that you might need to pass in the radix parameter into parseInt if your number is (or looks) octal or some other format.

Boolean vs Int in Javascript

I always assumed that booleans were more efficient than ints at storing an on/off value - considering that's their reason for existence. I recently decided to check if this is true with the help of jsperf, and it came up with some contrary results!
http://jsperf.com/bool-vs-int
Here is the first test I tried. Toggling the value of the on/off switch. On Chrome it's significantly faster to do this using 1/0, but on firefox it's slightly faster to do this using bool. Interesting.
http://jsperf.com/bool-vs-int-2
And here's the second test I tried. Using them in a conditional. This appears to have significant advantage for ints as opposed to bools, up to 70% faster to use 1/0 instead of booleans - on both firefox and chrome. Wtf?
I guess my question is, am I doing something wrong? Why are ints so much better at boolean's job? Is the only value of using bools clarity, or am I missing something important?
Disclaimer, I can only speak for Firefox, but I guess Chrome is similar.
First example (http://jsperf.com/bool-vs-int):
The Not operation
JägerMonkey (Spidmonkey's JavaScript methodjit) inlines the check for boolean first and then just xors, which is really fast (We don't know the type of a/b, so we need to check the type).
The second check is for int, so if a/b would be a int this would be a little bit slower.
Code
The Subtract operation.
We again don't know the type of c/d. And again you are lucky we are going to assume ints and inline that first. But because in JavaScript number operations are specified to be IEEE 754 doubles, we need to check for overflow. So the only difference is "sub" and a "conditional jump" on overflow vs. plain xor in case 1.
Code
Second example:
(I am not 100% sure about these, because I never really looked at this code before)
and 3. The If.
We inline a check for boolean, all other cases end up calling a function converting the value to a boolean.
Code
The Compare and If.
This one is a really complex case from the implementation point of view, because it was really important to optimize equality operations. So I think I found the right code, that seems to suggest we first check for double and then for integers.
And because we know that the result of a compare is always a boolean, we can optimize the if statement.
Code
Followup I dumped the generated machine code, so if you are still interested, here you go.
Overall this is just a piece in a bigger picture. If we knew what kind of type the variables had and knew that the subtraction won't overflow then we could make all these cases about equally fast.
These efforts are being made with IonMonkey or v8's Crankshaft. This means you should avoid optimizing based of this information, because:
it's already pretty fast
the engine developers take care of optimizing it for you
it will be even faster in the future.
your test was a bit off due to the definition of "function" and "var" and the call for the function. The cost to define function and variables and calling them will differ from engine to engine. I modified your tests, try to re-run with your browsers (note that IE was off because the first run was weird but consecutive runs were as expected where bool is fastest): http://jsperf.com/bool-vs-int-2/4
I don't know but in the second test it does
if(a) bluh();
vs
if(c == 1) bluh();
maybe c==1 is faster because you're comparing a value with one with the same type
but if you do if(a) then js need to check if the value evaluates to true, not just if it is true...
That could be the reason...
Maybe we need to test
if(c==1)
vs
if(a===true) with three =
For me the choice would be based on API usage. Always return that which is most useful. If I use secondary code, I'd favor methods that return booleans. This probably makes the code ready to be chained. The alternative is to provide overloaded methods.
Diggin' deep here. Regarding performance, I'm still unsure (this is why I found this thread) if booleans vs 0/1 is faster when computing and it still seems heavily browser-dependent. But take into account, that in extremely huge datasets the data has to be downloaded by the user first anyway:
"true" and "false" obv take up 4 or 5 characters respectively, whereas 0 and 1 are only 1 character. So it might save you a little bit of bandwidth at least, so less time to load and only after that is it up to the client's browser and hardware how to deal with those types, which seems pretty much negligible.
As a little bonus and to actually contribute something, since (I think?) no one mentioned it here, if you are going with the 0 and 1 approach, instead of using if-statements you can use bitwise operations to toggle between them, which should be pretty fast:
x=0;
x^=1; // 1
x^=1; // 0
This is the equivalence to using this toggle for booleans:
x=false;
x=!x; // true
x=!x; // false

Creating a Basic Formula Editor in JavaScript

I'm working on creating a basic RPG game engine prototype using JavaScript and canvas. I'm still working out some design specs on paper, and I've hit a bit of a problem I'm not quite sure how to tackle.
I will have a Character object that will have an array of Attribute objects. Attributes will look something like this:
function(name, value){
this.name = name;
this.value = value;
...
}
A Character will also have "skills" that are calculated off attributes. A skills value can also be determined by a formula entered by the user. A legit formula would look something like this:
((#attribute1Name + (#attribute2Name / 2) * 5)
where any text following the # sign represents the name of an attribute belonging to that character. The formula will be entered into a text field as a string.
What I'm having a problem with is understanding the proper way to parse and evaluate this formula. Initially, my plan was to do a simple replace on the attribute names and eval the expression (if invalid, the eval would fail). However, this presents a problem as it would allow for JavaScript injection into the field. I'm assuming I'll need some kind of FSM similar to an infix calculator to solve this, but I'm a little rusty on my computation theory (thanks corporate world!). I'm really not asking for someone to just hand me the code so much as I'd like to get your input on what is the best solution to this problem?
EDIT: Thanks for the responses. Unfortunately life has kept me busy and I haven't tried a solution yet. Will update when I get a result (good or bad).
Different idea, hence a separate suggestion:
eval() works fine, and there's no need to re-invent the wheel.
Assuming that there's only a small and fixed number of variables in your formula language, it would be sufficient to scan your way through the expression and verify that everything you encounter is either a parenthesis, an operator or one of your variable names. I don't think there would be any way to assemble those pieces into a piece of code that could have malicious side effects on eval.
So:
Scan the expression to verify that it draws from just a very limited vocabulary.
Let eval() work it out.
Probably the compromise with the least amount of work and code while bringing risk down to (near?) 0. At worst, a misuser could tack parentheses on a variable name in an attempt to execute the variable.
I think instead of letting them put the whole formula in, you could have select tags that have operations and values, and let them choose.
ie. a set of tags with attribute-operation-number:
<select> <select> <input type="text">
#attribute1Name1 + (check if input is number)
#attribute1Name2 -
#attribute1Name3 *
#attribute1Name4 /
etc.
There is a really simple solution: Just enter a normal JavaScript formula (i.e. as if you were writing a method for your object) and use this to reference the object you're working on.
To change this when evaluating the method use apply() or call() (see this answer).
I recently wrote a similar application. I probably invested far too much work, but I went the whole 9 yards and wrote both a scanner and a parser.
The scanner converted the text into a series of tokens; tokens are simple objects consisting of token type and value. For the punctuation marks, value = character, for numbers the values would be integers corresponding to the numeric value of the number, and for variables it would be (a reference to) a variable object, where that variable would be sitting in a list of objects having a name. Same variable object = same variable, natch.
The parser was a simple brute force recursive descent parser. Here's the code.
My parser does logic expressions, with AND/OR taking the place of +/-, but I think you can see the idea. There are several levels of expressions, and each tries to assemble as much of itself as it can, and calls to lower levels for parsing nested constructs. When done, my parser has generated a single Node containing a tree structure that represents the expression.
In your program, I guess you could just store that Node, as its structure will essentially represent the formula for its evaluation.
Given all that work, though, I'd understand just how tempting it would be to just cave in and use eval!
I'm fascinated by the task of getting this done by the simplest means possible.
Here's another approach:
Convert infix to postfix;
use a very simple stack-based calculator to evaluate the resulting expression.
The rationale here being, once you get rid of the complication of "* before +" and parentheses, the remaining calculation is very straightforward.
You could look at running the user-defined code in a sandbox to prevent attacks:
Is It Possible to Sandbox JavaScript Running In the Browser?

Categories

Resources