JavaScript inline functions like in C++ - javascript

Is there any ability in future ECMAScript standards and/or any grunt/gulp modules to make an inline functions (or inline ordinary function calls in certain places) in JavaScript like in C++?
Here an example of simple method than makes dot product of vectors
Vector.dot = function (u, v) {
return u.x * v.x + u.y * v.y + u.z * v.z;
};
Every time when I'am writing somethink like
Vector.dot(v1, v2)
I want be sure that javascript just do this calculations inline rather then make function call

Given that the OP asks for performance, I will try to provide an answer.
If you are optimizing for the V8 engine, you can check the following article to see which functions are inlined, and how deoptimization affects your code.
http://floitsch.blogspot.com/2012/03/optimizing-for-v8-inlining.html
For example, if you want to see if Vector.dot is inlined, use the following command line where script.js contains both your definition and calling code:
d8 --trace-inlining script.js
The optimization algorithm differs from engine to engine, but the inlining concept should be pretty much the same. If you want to know about other engines, please modify the question to including the exact engine in order to get some insights from JS engine experts.

Modern JS engines already inline functions when they identify that it is possible and useful to do that.
See http://ariya.ofilabs.com/2013/04/automatic-inlining-in-javascript-engines.html. Quote:
If you always worry about manual function inlining, this is a good time to revisit that thought. Simply write the code to be readable even if it means breaking the code into multiple small functions! In many cases, we can trust the modern JavaScript engines to automatically inline those functions.
I suppose you could write a pre-processor to handle inline keywords and do the necessary source code rewriting (and then wire it into gulp or grunt if you insist), but that would seem to be quite complex, and frankly most likely not worth the trouble.

Related

JavaScript is compiled or interpreted language or both?

I'm sorry for this silly question but I'm confusing about that.
I have been reading a you don't know JS yet book and the book said that
JS is most accurately portrayed as a compiled language.
And they explain with some example and that makes sense for me
But when I'm searching on the internet. Most people suppose that JS is an interpreted language.
I read that JS engine uses many kinds of tricks to handling JS programs like JIT, hot-recompile.
So should I consider Javascript to be both compiled and interpreted language?
UPDATE:
When JavaScript first came in 1995-96, Brendan Eich created the very first JS-Engine called spider-monkey (Still used in Mozilla Firefox). At this time JavaScript was created keeping Browsers in mind. So that any file coming from the Servers would be quickly interpreted and shown by the Browsers.
Interpreter was a best choice to do so, since Interpreters
executes code line by line and shows the results immediately.
But as time progressed Performance became an issue, It was becoming slower and slower. The problem with Interpreters is that when you are running the same code over and over again in a loop like this one:
const someCalculation = (num1, num2) => {
return num1 + num2;
};
for (let i = 0; i < 10000; i++) {
someCalculation(5, 6); // 11
}
It can get really really slow.
So the best option was introducing the Compiler,
which actually helps us here. It takes a little bit more time to start up, because it has to go through the compilation step at the beginning - Go through our code, understand it and spit it out into another language. But the Compiler would be smart enough. When it sees the code like above ( where we loop over and it has the same inputs , returning the same outputs), it can actually just simplify this code and instead of calling this function multiple times it can just replace this function with output for the function. Something like this.
const someCalculation = (num1, num2) => {
return num1 + num2;
};
for (let i = 0; i < 10000; i++) {
11; // And it will not call someCalculation again and again.
}
Because the Compiler does not repeat the translation for each pass through in that loop, the code generated from it is actually faster.
And these sorts of edits that Compilers do are called Optimizations
Thus Javascript combined both Interpreter and Compiler to get the best of both the world. So Browsers started mixing compilers called JIT-Compilers for just-in-time compilations to make the engines faster.
In the Image you can see a Profiler which keeps a watch on the repeated code and passes it on to the Compiler for Code Optimizations.
This means that the Execution Speed of Javascript Code that we entered
into the engine is going to
gradually improve because the Profiler and Compiler are constantly
making updates and changes to our Byte code in order to be as
efficient as possible. So Interpreter allows us to run the code right
away while Profiler and Compiler allows us to optimize this code as
we are running.
Now Let's come to some conclusions:
Now that we know how JS-Engine works underneath the hood, we as Programmers can write more Optimized Code - code that the Compiler can take and run it faster than our regular Javascript. However,
We need to make sure we don't confuse this Compiler- because the Compiler is not perfect, it can make mistakes and it may try to optimize the code that exactly does the opposite. And if it makes a mistake and it does something unexpected, it does something called De-Optimization which takes even more longer time to revert it back to the interpreter.
NOW THE BIG QUESTIONS : Is Javascript an interpreted language?
ANSWER : Yes, initially when Javascript first came out, you had a Javascript engine such as spider-monkey- created by Brenden Eich that interpretted javascript to Byte Code and this Javascript engine was able to run inside of our browser to tell our Computers what to do.
But things have evolved now, we don't just have interpreters, we also use compilers to optimize our code. So, this is a common misconception.
When someone says Javascript is an interpreted language, yes there is
some truth to it but it depends on the implementation. You can make an
implementation of Javascript Engine that perhaps only compiles.
Technically it all matters depending on the implementation.
Javascript is initially an interpreted language. When it encounters a bit of code for the first time it reads the tokens one by one and executes them exactly according to specification. This is level 0.
If a bit of code is executed often, let's say 100 times (exact number depends on the browser) it is considered "warm". The browser precomputes the tokenization and basic operations into a slightly faster bytecode. At this stage, no assumptions are made and the bytecode is completely equivalent to the original code. This is level 1.
If code is executed more often, let's say 10,000 times and the types of the parameters are always the same, a further compilation step can be executed. Many javascript operators do wildly different things depending on the types. Every operator has some logic to check what variant of the operator to perform (eg adding or concatenation). Also different amounts of memory need to be allocated to different types of objects. Performing the type checks once at the top of the function and allocating all the memory at once if much faster. This is level 2.
Depending on the browser, there might be more optimization levels, usually by making stricter assumptions about the parameters. There might be a more efficient addition for integers. Of course, if you ever call the function with a different variable type, the browser has to execute unoptimized raw JS again.
Practical Advice
This all happens under the hood and as a programmer you most likely won't ever have to worry about this. The optimization will never change the big O speed of your program, which is usually the cause of most slow software. You might be able to slightly increase the speed by making sure the types of the parameters of your most called functions are consistent, though not enough to be worth the trouble.
Check the MDN
this is the place where you get the most accurate information
To quote MDN on the topic:
JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language
Basically since JS is used in multiple environments it can be either one or the other.

How to avoid using JavaScript eval() in user-defined function

I'm trying to make a generic table-top RPG helper web app. It has to be generic because Wizards of the Coast is very protective of their copyrights. So, in order to avoid cease-and-desists, the system has to be capable of loading arbitrary rules. That said, my buddies and I (along with most any other user) will be using it for D&D.
In D&D, modifiers are based on a character's stats. To get a modifier, you take the stat, subtract 10, divide by 2, and round down.
function getModifier(statValue) {
return Math.floor((statValue - 10) / 2);
}
My app will be capable to loading a game's rules from a .json file. I want to be able to make this modifier function user-definable. The easiest way would be to just eval() whatever they provide in the .json file, but obviously that's a terrible idea due to security issues.
Unfortunately, I can't think of a simple way to get around this in a secure manner. Obviously I could write my own parser, but that's more complicated than I'd like/am currently capable of.
Ideas?
I did a quick google search and found two options - http://mathjs.org and http://jsep.from.so
btw. writing your own parser is not that difficult. You may be able to write one that's sufficient for your purpose in less than 100 lines of code
First, bear in mind that this is all on the client-side. So long as you trust the JSON (it came from your server or it is controlled alongside the application itself), then you can use it. That doesn't completely rule out some trojan inserting malicious rules, but I don't think botnets have learned to play D&D yet.
To literally avoid eval and provide some modicum of security, you can use new Function. It takes a list of argument names followed by the function body, allowing you a large amount of control over how the function is defined and where it can be referenced from. You only need to store the body in the JSON file, allowing you to largely control the parameters and make it difficult to assign to the global scope, minimizing your attack surface (such as it is) quite a lot.
If you want to have fun with this and now your rules will largely be mathematical, you may consider using a tool like pegjs to generate a parser for your rules. Calculators are one of the classic introductions to parsers and compilers, so this could be an opportunity to play with some fun tech. The rules and parsers built by pegjs are very easy to use in a JS project (I have an example using PegJS and ES6 via Babel).
There are two options as I see it. One, if you 100% want to define the function in .json, you will need to parse. JSON does not allow functions, so you need to store the function as a string and eval it.
The better way would be to also provide a config.js ability. Perhaps the .json would have a "configUrl": property, and then expose well known apis, eg RPGHelper.setModifer(someFunction) that you can call from inside the config.js file. The user is then free to define whatever arbitrary logic there.
One solution to your problem is to use sandboxed iframes (current supported by all major browsers
You run user code on a separate page, with limited priviliges, in such a way that the code does not interfere with the rest of the application. You can communicate with the sandboxed page using postMessage() and window.onmessage.

Convert Actionscript to Javascript

I was just wondering is there anyway to convert Actionscript to Javascript. When I say Actionscript I mean Actionscript 3. I've used google swiffy but Actionscript 3 is hardly supported. I've also heard of Jangaroo but its not what I want. Even if its a code comparison! Thanks!
Javascript and ActionScript (especially AS3) are syntactically similar languages and both are based on the ECMAScript Specification. There are some small differences in the actual code such as:
//Actionscript:
var a:String = new PlayerName();
//JavaScript:
var a = new PlayerName();
This is a demonstration that JavaScript does not have explicit variable type declarations, but this is not the real problem.
What you're asking goes much further than syntactic incompatibilities, as JS and AS work with completely different APIs. ActionScript has stages, frames and other Flash-based things which do not exist in JavaScript's environment. JavaScript - usually running in a browser - is used to manipulate documents, DOM nodes and CSS properties.
This means that unless you're just doing simple function calls and mathematics (without any dependency on the user or their environment) the things your program is doing simply cannot be transferred to another environment. For example, you cannot tell JavaScript to play() or goToAndStop() because there are no frames to play, stop or go to in a HTML document.
Unfortunately, I think what you're wondering is valid, but the question is almost certainly incorrect. If you have an application created in Flash or any other AS-enabled environment, you probably want to think about porting or re-writing it to the new context.
You might have a look at Falcon JS: https://github.com/apache/flex-falcon
http://www.gotoandlearn.com/play.php?id=172
Just check it out the above. It might be useful.

Learning how JavaScript optimizes execution, if at all

Is there a way to learn at how JavaScript is interpreted and executed? In .NET or JAVA for instance, you could look at the generated byte code, in C you could look at the generated assembly instruction but from what I gather, JavaScript is interpreted line by line and then it varies on the JS engine in different browsers.
Still is there a way to learn how JavaScript does this? Does the interpreter in modern browsers tend to look ahead and optimize as a compiler might?
For instance, if I did:
$('#div1').css('background-color','red');
$('#div1').css('color','white');
Could I have a perf gain by doing:
var x = $('#div1');
x.css('background-color','red');
x.css('color','white');
The point of this question is to get some information how one might gain some insight as to how JavaScript is run in the browser.
The optimization steps taken, as always, depend on the compiler. I know that SpiderMonkey is fairly well documented, open source, and I believe does JIT compilation. You can use it outside of the browser to tinker with, so that's one less black-box to deal with when experimenting. I'm not sure if there's any way to dump the compiled code as it runs to see how it optimizes in your code, but since there's no standard concept of an intermediate representation of Javascript (like there is with .NET/Java bytecode) it would be specific to the engine anyway.
EDIT: With some more research, it does seem that you can get SpiderMonkey to dump its bytecode. Note, however that optimizations can take place both in the interpreter that generates the bytecode and the JIT compiler that consumes/compiles/executes the bytecode, so you are only halfway there to understanding any optimizations that may occur (as is true with Java and .NET bytecodes).
V8 does some amazing things internally. It compiles to machine code and creates hidden classes for your objects. Mind-blowing details here: https://developers.google.com/v8/design
Ofcourse when it comes to the DOM, performing lookups can only go that fast. Which is why chaining or temp variables can make a difference, especially in loops and during animations.
Besides that, using the right selectors can be helpful. #id lookups are undoubtedly the fastest. Simple tagname or class lookups are reasonably fast as well. jQuery selectors like :not can't fall back on builtins and are considerably slower.
Besides reducing lookups, another good rule of thumb with the DOM is: If you need to do a lot of DOM manipulation, take out some parent node, do the manipulations, and reinsert it. This could save a whole lot of reflows/repaints.
Yes, you will get a performance gain. The DOM is not queried twice, and only one jQuery object is instantiated.
Yet you should not do this for performance (the gain will be negligible), but for code quality. Also, you do not need a variable, jQuery supports chaining:
$('#div1').css('background-color','red').css('color','white');
and the .css method also can take an object:
$('#div1').css({'background-color': 'red', 'color': 'white'});

Is Jquery *compiler* possible?

When I saw this question I thought it would be helpful if a jQuery compiler could be written. Now, by compiler, I mean something that takes in jQuery code and outputs raw javascript code that is ultimately executed.
This is how I vision a block of jQuery code execution:
a jQuery function is called and parameters are passed to it
the function calls a raw javascript function and passes the parameters it received to it
the newly called function performs the intended action
I understand that this is a very simplified model and it could be much more complex, but I think the complexity is reduced to steps 2 and 3 being repeated with different raw js functions being called and each time fed with all or a subset of parameters / previous results.
If we subscribe to that model, then we might come up with methods to make the jQuery functions perform double-duty:
What they already do
Logging what they did in form of raw_function(passed_params)
Am I making some wrong assumptions that would make this impossible?
Any ideas how Firebug's profiler attempts to get function names? Could it be used here?
Edit
What I was thinking was making a black box with input / output as:
normal jquery code → [BB] → code you'd write if you used no library
I called this a compiler, because you compiled once and then would use the resulting code.
I argued that it could have at least educational use, and probably other uses as well.
People said this would take in a small amount of code and output a huge mass; that does not defy the intended purpose as far as I see
People said I'd be adding an extra, needless step to page rendering, which, given only the resulting code would ultimately be used (and probably be used just for studying), is not correct.
People said there is no one-to-one relation between javascript functions and jquery functions, and implied such a converter would be too complicated and probably not worth the effort. With this I now agree.
Thank you all!
I think what you mean is: if you write
var myId = $("#myId")
it will be converted to
var myId = document.getElementById("myId")
I think its possible, but the problem is, jQuery functions return jQuery objects, so in the above example, the first myId will be a jQuery object & the second will be a node object(i think) which will affect other functions that needs to use it later in the code after compilation. Especially if they are chained
secondly you will have to be sure that the conversion actually has performance benefits.
However if you are aware of all this and you can plan you code accordingly, i think it will be possible
If the purpose of the compiler to convert Javascript (which may be jquery or anything) to better Javascript (which I understood from you saying "ultimately executed"), then Google has already done that. They made closure compiler and some have tried it with JQuery in this post. Isn't this what you are suggesting ?
jQuery code is "raw JavaScript code" so I'm not sure what a compiler would really buy you. That's like writing a C# compiler which takes C# 4.0 code and emits C# 1.1 code. What's the benefit?
jQuery isn't a different language which replaces or even sits on top of JavaScript. It's a framework of JavaScript code which provides lots of useful helpers for common tasks. In my view, it's greatest benefit is that its distinctive structure helps to differentiate it from the more "Java-like" languages.
JavaScript by itself is deceptively similar to other languages and this tends to be one of its biggest faults as a language. People try to think of it in terms of Java, even though the similarities pretty much stop at the name. Structurally, JavaScript is very different in many ways (typing, scope, concurrence, inheritance, polymorphism, etc.) and I particularly like how jQuery and other modern JavaScript projects have brought the language to stand on its own merits.
I guess to get back to the question... If you're looking to turn jQuery-style JavaScript into Java-style JavaScript, then that's something of a step backwards. Both versions would be interpreted by the browser the same way, but one of the versions is less elegant and represents the language more poorly than the other.
Note that jQuery isn't the only framework that does these things, it's just the most popular. Would such a compiler need to also handle all the other frameworks? They all do different things in different ways to take advantage of the language. I don't think that homogenizing them to a "simpler" form buys us anything.
Edit: (In response to the various comments around this question and its answers, kind of...
How would you structure this compiler? Given that (as we've tried to point out) jQuery is JavaScript and is just a library of JavaScript code, and given how browsers and JavaScript work, your "compiler" would just have to be another JavaScript library. So essentially, what you want is to go from:
A web page
The jQuery library
Some JavaScript code which uses the jQuery library
to:
A web page
The jQuery library
Some JavaScript code which uses the jQuery library
Your "compiler" library
Some more JavaScript code which sends the previous JavaScript code through your library somehow
Your "jQuery-equivalent" library
Some more JavaScript code which replaces the original JavaScript code with your new version
in order to make things simpler? Or to somehow make debugging tools like FireBug easier to use? What you're proposing is called an "obfuscator" and its sole purpose is to make code more difficult to reverse-engineer. A side effect is that it also make code more difficult to understand and maintain.
Now, by compiler, I mean something
that takes in jQuery code and outputs
raw javascript code that is ultimately
executed.
I think that statement may indicate what's going wrong for you.
jQuery is a library implemented in the Javascript language. jQuery isn't a language separated from Javascript. jQuery is a collection of Javascript code that you can use to make Javascript development easier. It's all Javascript. A "jQuery compiler" to convert "jQuery code" to "raw Javascript" would be quite useless because jQuery is raw Javascript.
What you probably actually want is a Javascript compiler. In that case, it's certainly possible. In fact, some web browsers nowadays actually "compile" on the Javascript code in some kind of bytecode to enhance performance. But development workflows involving Javascript typically don't involve a compiler tool of some kind.
Apparently what you actually want is to "inline" jQuery code into your code, sort of like this:
var myfoo = $('#foo'); → var myfoo = document.getElementById('foo');
This is actually something a C++ compiler would do to optimize performance, but Javascript is not C++ so it doesn't apply here.
I don't see how this is useful. The point of jQuery is to simplify Javascript development by providing a consistent interface like the $() function. By performing this "inlining" procedure you produce code that is even harder to read and maintain.
And why add an extra step? Why not just deliver the application javascript code and the jQuery library to the browser? Why add an extra step involving an extra tool to convert Javascript to Javascript that doesn't provide any substantial extra benefits?

Categories

Resources