I've seen the term "Low level Javascript" come up a few times but I've no idea what it means. Google shows no results surprisingly. Can someone shed some light on it?
As of 2012, someone saying "low level JavaScript" could be refering to LLJS. It's a subset of JavaScript that compiles to a JavaScript code that is garbage collector friendly but unreadable (making heavy usage of WebGL typed arrays to manage memory).
I would say it is "javascript without using cross-browser frameworks" such as jQuery or YUI.
Can be particularly tricky when it comes to supporting multiple browsers.
Sometimes people make up their own terms when they shouldn't. "Low level Javascript" is one of them. There's nothing "low level" about Javascript. It's interpreted at run-time inside an environment of high-level abstractions, like the DOM.
It's a very specialized tool that allows You to write CPU and Memory (explicit memory management, not GC) optimized JavaScript code. Using binary data, not standard JS objects and types.
Why? Because in some cases You need top performance.
I suppose it means Javascript without any framework such as prototype/jQuery/YUI, which help with cross-browser compatibility, and generally provide a lot of useful functions, so you don't have to spend your time re-inventing the wheel.
Also, maybe it has something to do with the "new" way of doing Javascript -- i.e. object-oriented, using Frameworks, ... In opposition to the crappy code we used to seen a couple of years ago.
low level JS is concise, precise code that executes efficiently, usually taking advantage of the language's intricacies
bitwise operation, type conversions / short circuit logical operators, prototype chaining, context binding, ternary assignation, event bubbling / propagation, object referencing, using the GPU, etc.
Related
I come from a background in Haskell. I'm very used to getting things done with recursive functions and the typical higher-order functions (folds, maps, filters, etc) and composing functions together. I'm developing in node.js now, and I'm seriously tempted to write my own modules implementing these functions so I can use them in my code in a way that makes sense to me.
My question is, basically: is Javascript set up to handle this type of burden? I understand that the aforementioned recursive functions can be easily refactored into iterative ones, but often times I find myself calling a lot of functions within functions, and I don't know if Javascript can handle this type of thing well. I know that things like Underscore exist and implement some FP principles, but my question basically boils down to: is it good practice to program functionally in Javascript? If not, why not?
I also apologize if this question is a little too soft for SO, but I don't want to start putting together my own tool set if it's just going to break everything once it gets too large.
In my opinion, the short answer to your question is yes -- applying functional programming principles is viable in Javascript! (I believe that this is also true for most other languages -- there's usually something to be gained from applying FP principles).
Here's an example of a functional parser combinator library I built in Javascript. (And here it is in action). It was important to be functional because: 1) it allows me to build parsers by composition, which means I can build and test small parsers independently, then put them together and have confidence that the behavior will be the same, and 2) it makes backtracking super easy to get right (which is important because the choice operator backtracks when an alternative fails).
So these are FP principles (note the absence of recursion, folds, maps, and filters from this list) that I found extremely useful in building my library:
avoiding mutable state
pure functions (i.e. output depends only on input)
composition: building complex apps by gluing together simple pieces
It's usually quite easy and pleasant to apply these in Javascript because of Javascript's support for:
first-class functions
anonymous functions
lexical closures
but here are some things to watch out for:
lack of popular library of efficient functional data structures
lack of tail-call optimization (at least at the moment)
partial application is more syntax-heavy than in Haskell
lots of popular libraries are not especially functional
the DOM is not functional (by design)
However, your last comment -- "I don't want to start putting together my own tool set if it's just going to break everything once it gets too large" -- is a good one. This is basically a problem for every approach, and I can't tell you whether FP in Javascript will be more problematic than "mainstream" techniques when things get too large. But I can tell you that in my experience, FP in Javascript helps me to prevent things from getting too large.
I've read the article about Google's upcoming DASH/DART language, which I found quite interesting.
One thing I stumbled upon is that they say they will remove the inherent performance problems of JavaScript. But what are these performance problems exactly? There aren't any examples in the text. This is all it says:
Performance -- Dash is designed with performance characteristics in
mind, so that it is possible to create VMs that do not have the performance
problems that all EcmaScript VMs must have.
Do you have any ideas about what those inherent performance problems are?
This thread is a must read for anyone interested in dynamic language just in time compilers:
http://lambda-the-ultimate.org/node/3851
The participants of this thread are the creator of luajit, the pypy folks, Mozilla's javascript developers and many more.
Pay special attention to Mike Pall's comments (he is the creator of luajit) and his opinions about javascript and python in particular.
He says that language design affects performance. He gives importance to simplicity and orthogonality, while avoiding the crazy corner cases that plague javascript, for example.
Many different techiques and approaches are discussed there (tracing jits, method jits, interpreters, etc).
Check it out!
Luis
The article is referring to the optimization difficulties that come from extremely dynamic languages such as JavaScript, plus prototypal inheritance.
In languages such as Ruby or JavaScript, the program structure can change at runtime. Classes can get a new method, functions can be eval()'ed into existence, and more. This makes it harder for runtimes to optimize their code, because the structure is never guaranteed to be set.
Prototypal inheritance is harder to optimize than more traditional class-based languages. I suspect this is because there are many years of research and implementation experience for class-based VMs.
Interestingly, V8 (Chrome's JavaScript engine) uses hidden classes as part of its optimization strategy. Of course, JS doesn't have classes, so object layout is more complicated in V8.
Object layout in V8 requires a minimum of 3 words in the header. In contrast, the Dart VM requires just 1 word in the header. The size and structure of a Dart object is known at compile time. This is very useful for VM designers.
Another example: in Dart, there are real lists (aka arrays). You can have a fixed length list, which is easier to optimize than JavaScript's not-really-arrays and always variable lengths.
Read more about compiling Dart (and JavaScript) to efficient code with this presentation: http://www.dartlang.org/slides/2013/04/compiling-dart-to-efficient-machine-code.pdf
Another performance dimension is start-up time. As web apps get more complex, the number of lines of code goes up. The design of JavaScript makes it harder to optimize startup, because parsing and loading the code also executes the code. In Dart, the language has been carefully designed to make it quick to parse. Dart does not execute code as it loads and parses the files.
This also means Dart VMs can cache a binary representation of the parsed files (known as a snapshot) for even quicker startup.
One example is tail call elimination (I'm sure some consider it required for high-performance functional programming). A feature request was put in for Google's V8 Javascript VM, but this was the response:
Tail call elimination isn't compatible with JavaScript as it is used in the real
world.
How much overhead is there when use functions that have a huge body?
For example, consider this piece of code:
(function() {
// 25k lines
})();
How may it affect loading speed / memory consumption?
To be honest I'm not sure, the good way to help answer your question is to measure.
You can use a javascript profiler, such as the one built into Google Chrome, here is a mini intro to the google chrome profiler
You can also use Firebug profiler() and time(): http://www.stoimen.com/blog/2010/02/02/profiling-javascript-with-firebug-console-profile-console-time/
Overhead is negligible on a static function declaration regardless of size. The only performance loss comes from what is defined inside the function.
Yes, you will have large closures that contain many variables, but unless your declaring several tens of thousands of private variables in the function, or executing that function tens of thousands of times, then you won't notice a difference.
The real question here is, if you split that function up into multiple smaller functions, would you notice a performance increase? The answer is no, you should actually see a slight performance decrease with more overhead, although your memory allocation should at least be able to collect some unused variables.
Either way, javascript is most often only bogged down by obviously expensive tasks, so I wouldn't bother optimizing until you see a problem.
Well that's almost impossible to answer.
If you realy want to understand about memory usage, automatic garbage colection and other nitty gritty of closure, start here: http://jibbering.com/faq/notes/closures/
Firstly, products like JQuery are built on using closures extremely heavily. JQuery is considered to be a very high performance piece of Javascript code. This should tell you a lot about the coding techniques it uses.
The exact performance of any given feature is going to vary between different browsers, as they all have their own scripting engines, which are all independantly written and have different optimisations. But one thing they will all have done is tried to give the best optimisations to the most commonly used Javascript features. Given the prevelance of JQuery and its like, you can bet that closures are very heavily optimised.
And in any case, with the latest round of browser releases, their scripting engines are all now sufficiently high performance that you'd be hard pushed to find anything in the basic language constructs which consitutes a significant performance issue.
I'm pretty efficient in jQuery, having implementing it in several projects for my company. However, I found myself a little lost when reading stuff like node.js.
Do I have to go back to basics and learn the JavaScript language or should I just stick with jQuery?
One more thing I would like to ask: Does coding in plain JavaScript increase performance compared to coding with jQuery? For my own experience, coding heavy, complex combination of animation in jQuery always seems to take up large amount of the computer memory.
You should understand what's going on, to a degree. It doesn't hurt to know what's underneath, but sometimes that's not optimal to know everything either, for example: is .innerHTML consistent? Not completely, e.g. <select> in IE. Does that mean you need to know every inconsistency? Not if you're letting jQuery handle it.
People say you need to understand JavaScript before jQuery, let me say I agree, however there are limits to that though, you don't necessarily need to know every quirk and inconsistency between browsers for example, that's why we use an abstraction layer.
To me, this is no different than saying you need to learn assembly before C#, should you know what's happening, how memory is referenced, what a pointer is? I think so, do you need to know every detail? Probably not. We would never progress if every new programmer goes through learning every layer beneath, this is why math theorems build upon others known to be true, same concept.
You should be able to trust your abstraction layer. Is this always true? unfortunately not, but jQuery does a pretty good job at being as consistent as possible and always improving. More importantly, the community does a good job of making the inconsistencies known.
Edit: Let me caveat everything above by saying if you can learn what's underneath do so (this applies to most any abstraction in my book, not just JavaScript), it will help you program better and more efficiently. If you know what's going on under the covers, you can more optimally take advantage of it.
It's a lot like apples and oranges, actually. jQuery is awesome library but it focuses on DOM manipulations. It does not help you much with general coding, prototype inheritance, closures, data types and other important stuff you have to deal with when programming.
node.js have nothing to do with DOM, so it is very much orthogonal to jQuery, no wonder you have trouble understanding it.
Note, however, that knowledge of JavaScript won't necessarily mean you'll be efficient with every JavaScript library out there. Each library makes kind of a superset of a language, a domain specific language to help with specific task that library was built to solve. You will always have to learn that DSL first to be efficient but it'll be easier to understand internals of any given library if you know JavaScript well.
If you are only interested in application programming (web sites and applications) then jQuery is more than adequate. If you want to develop a JavaScript framework or library, then proficient knowledge of the JavaScript language is necessary.
Does being good in jQuery imply being good in JavaScript?
No. I strongly suggest you learn the basics and then some.
jQuery is just a library. While productive, being well versed in the functionality that a library provides is not the same as being good at the language in which that library is written in.
I'm not saying that you need to know that all bitwise operations are converted to signed 32-bit integers in big-endian order, but you do need to know about core concepts like closures, how to properly attach event handlers, and the basic concepts of asynchronous/event oriented programming.
What if you were to change jobs to a company that uses ExtJs instead of jQuery? Understanding the core concepts of the language will make these sorts of transitions non-problematic.
Another thing to consider is that for every library, there is always a task that it doesn't support. Being reliant on a library to always do the heavy lifting will eventually bite you in the hind parts.
Does coding in plain JavaScript increase performance compared to coding with jQuery?
Libraries typically aim to be as generic as possible for the area of use they are targeting. Because of this, inefficiencies may occur in some scenarios that could be otherwise optimized outside of the library.
It all depends on how adept you are at JavaScript, algorithm selection/creation/analysis, and programming in general. When you start concerning yourself with being as high performing as possible, you really need to be able to get down to the finer details of a language. "Being good" at jQuery, or any library for that matter, will likely not help you with this (unless you're looking under the hood and implementing their techniques in a manner that is specific to your scenario).
jQuery is just a list of (very) useful functions, written in JavaScript.
You are just using the library without understanding what's behind it
and how things work. Most of the time you will only need jQuery for maybe 20%-40%
of your code, and the rest will be pure JavaScript, so I encourage you to learn the
basics. These are good places to start with:
http://www.w3schools.com/jsref
http://howtonode.org/what-is-this
http://net.tutsplus.com/tutorials/javascript-ajax/the-basics-of-object-oriented-javascript/
http://ejohn.org/apps/learn/
I'm a bit ambiguous on this. Knowing real deep JavaScript is a great art - I am always in awed silence when one of our resident deep JavaScript experts comes to the table. However, not everyone needs that kind of deep knowledge - if you're focused on building interfaces, knowing one of the frameworks well may be everything you ever need, with very few edge cases.
On the other hand, knowing at least the basics of how JavaScript works under the hood can only be beneficial. If you feel driven to take a look into it, I'd say do it. You don't have to become a total guru in fundamental JavaScript but having a basic idea of how data is handled internally, how events are processed by the browser, how memory is managed, etc. is a good thing.
Not necessarily, it is like saying like being good in Java is same being good in byte code since it is using the byte code.
jQuery is an abstraction layer for JavaScript, and for this reason most of the time you will be doing it all in jQuery rather than raw JavaScript. However, it is always a good idea to have some JavaScript knowledge at least for the required parts.
For this reason, if you see any jQuery book out there, most of them have a chapter or index regarding the "Basics Of JavaScript" or "JavaScript for jQuery".
By now, most mainstream browsers have started integrating optimizing JIT compilers to their JavaScript interpreters/virtual machines. That's good for everyone. Now, I'd be hard-pressed to know exactly which optimizations they do perform and how to best take advantage of them. What are references on optimizations in each of the major JavaScript engines?
Background:
I'm working on a compiler that generates JavaScript from a higher-level & safer language (shameless plug: it's called OPA and it's very cool) and, given the size of applications I'm generating, I'd like my JavaScript code to be as fast and as memory-efficient as possible. I can handle high-level optimizations, but I need to know more about which runtime transformations are performed, so as to know which low-level code will produce best results.
One example, from the top of my mind: the language I'm compiling will soon integrate support for laziness. Do JIT engines behave well with lazy function definitions?
This article series discusses the optimisations of V8. In summary:
It generates native machine code - not bytecode (V8 Design Elements)
Precise garbage collection (Wikipedia)
Inline caching of called methods (Wikipedia)
Storing class transition information so that objects with the same properties are grouped together (V8 Design Elements)
The first two points might not help you very much in this situation. The third might show insight into getting things cached together. The last might help you create objects with same properties so they use the same hidden classes.
This blog post discusses some of the optimisations of SquirrelFish Extreme:
Bytecode optimizations
Polymorphic inline cache (like V8)
Context threaded JIT (introduction of native machine code generation, like V8)
Regular expression JIT
TraceMonkey is optimised via tracing. I don't know much about it but it looks like it detects the type of a variable in some "hot code" (code run in loops often) and creates optimised code based on what the type of that variable is. If the type of the variable changes, it must recompile the code - based off of this, I'd say you should stay away from changing the type of a variable within a loop.
I found an additional resource:
What does V8 do with that loop?