So I know that in Javascript instantiating a regex causes it to be compiled automatically and if that regex is stored in a variable it will be reused without recompiling. Example:
var re = /[Ff]oo|[Bb]ar/;
"Foo".match(re); // ["Foo"]
"Baz".match(re); // null
However, are duplicated regular expressions recompiled or does V8 (Chrome/Node.js) intelligently re-use them (like PHP does with preg_* functions)?
function isFooBar(str) {
return str.match(/[Ff]oo|[Bb]ar/);
}
isFooBar("Foo"); // ["Foo"]
isFooBar("Baz"); // null
So to clarify, I know the first example results in one compilation of the regex. But what about the second example?
Well, let's find out.
// http://stackoverflow.com/questions/3466850/complex-password-regular-expression
function isFooBar(str) {
return str.match(/^(?:(?=.*[a-z])(?:(?=.*[A-Z])(?=.*[\d\W])|(?=.*\W)(?=.*\d))|(?=.*\W)(?=.*[A-Z])(?=.*\d)).{8,}(?:(?=.*[a-z])(?:(?=.*[A-Z])(?=.*[\d\W])|(?=.*\W)(?=.*\d))|(?=.*\W)(?=.*[A-Z])(?=.*\d)).{8,}(?:(?=.*[a-z])(?:(?=.*[A-Z])(?=.*[\d\W])|(?=.*\W)(?=.*\d))|(?=.*\W)(?=.*[A-Z])(?=.*\d)).{8,}(?:(?=.*[a-z])(?:(?=.*[A-Z])(?=.*[\d\W])|(?=.*\W)(?=.*\d))|(?=.*\W)(?=.*[A-Z])(?=.*\d)).{8,}(?:(?=.*[a-z])(?:(?=.*[A-Z])(?=.*[\d\W])|(?=.*\W)(?=.*\d))|(?=.*\W)(?=.*[A-Z])(?=.*\d)).{8,}(?:(?=.*[a-z])(?:(?=.*[A-Z])(?=.*[\d\W])|(?=.*\W)(?=.*\d))|(?=.*\W)(?=.*[A-Z])(?=.*\d)).{8,}(?:(?=.*[a-z])(?:(?=.*[A-Z])(?=.*[\d\W])|(?=.*\W)(?=.*\d))|(?=.*\W)(?=.*[A-Z])(?=.*\d)).{8,}(?:(?=.*[a-z])(?:(?=.*[A-Z])(?=.*[\d\W])|(?=.*\W)(?=.*\d))|(?=.*\W)(?=.*[A-Z])(?=.*\d)).{8,}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=.*[##$%^&+=]).*$)?(^(?=.*\d)(?=.*[A-Z])(?=.*[##$%^&+=]).*$)?(^(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=]).*$)?(^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$)?(^(?=.*\d)(?=.*[a-z])(?=.*[##$%^&+=]).*$)?(^(?=.*\d)(?=.*[A-Z])(?=.*[##$%^&+=]).*$)?(^(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=]).*$)?$/);
}
console.time('1');isFooBar("Foo");console.timeEnd('1');
console.time('2');isFooBar("Bar");console.timeEnd('2');
(Open your console and run the code snippet above to see if the results for your browser.)
On Node.js 0.10.36 (V8 3.14.5.9):
1: 65ms
2: 0ms
On io.js 1.6.3 (V8 4.1.0.27):
1: 32ms
2: 0ms
So, I guess the answer to your question is YES, V8 is capable of automatically caching the regex.
EDIT:
Even though V8 is capable of such optimization, it might not in fact choose to always use this optimization. V8 has many complex heuristics for different cases, like when to inline a function, when to optimize a function, when to de-optimize a function, etc. Unless you are a V8 developer, many of these heuristics would appear to be bizarre or unexpected or both.
Not being a V8 developer myself, I do not know the answer to the specific question or if regexes are always automatically cached. However, even if I do know the answer, it may change in the future. So when you are writing code, I would still recommend storing the regex in such a way that it is clear what the intention for this variable is. And for the example above, this means lifting the regex variable out of the function isFooBar().
Another issue is how this regex is created. The example above and in OP's question are declared with a regular expression literal. However, if you are using the new RegExp() constructor, V8 would not be allowed to cache the regex since it might change during runtime.
http://code.google.com/p/v8/issues/detail?id=933#c3
In Chrome 9 we have removed a primitive caching of RegExp results. That means that we no longer take unrealistically low time for repeating the same operation on the same input over and over again.
The caching was originally added to make a point about benchmarks that were too simplistic (our own, at that time, included) being too easy to "game" by adding such caching (which makes no difference in real-world scenarios). Most benchmarks have since improved so much that we decided to remove the caching (and its unavoidable overhead).
The cache was added in v8 revision 4083 (released in Chrome 5) and removed in revision 5755 (will be in Chrome 9)
Related
Question for the v8 developers/experts.
Is it correct to assume, that v8 will completely eliminate the dead code, structured like this:
module1.js
export const DEBUG = false
module2.js
import { DEBUG } from './module1.js'
if (DEBUG) {
// dead code eliminated?
}
Please no comments like - "the overhead of 'if' check is very small and you should XXX instead of asking this question", I just want to know if v8 is capable of this (yes/no, preferably with a little details of course).
Thank you!
V8 developer here. The answer is, as so often, "it depends".
V8's optimizing compiler supports dead code elimination, so yes, under the right circumstances, a conditional branch that can never be taken will get eliminated.
That said, in the specific example you posted, the top-level code won't get optimized (probably -- depends on what else is in there), so in that case no, the if (DEBUG) check will be compiled (to unoptimized bytecode) and executed -- once, because executing it once is way faster than first trying to optimize (and possibly eliminate) it.
Another thing to consider is that V8 compiles functions "lazily", i.e. on demand. That means if you have an entire function that never gets called (e.g. because its only call site is in an if (DEBUG)-block and DEBUG is false), then that function won't even get compiled to bytecode, much less optimized code. That isn't dead code elimination in the traditional meaning of the term, but one could say that it's even better :-)
In conclusion: if you have a little DEBUG-code sprinkled over your app, it's totally fine to leave it in. Either it'll be in rarely executed paths, in which case the cost of executing the checks doesn't matter; or it'll be in hot paths, in which case V8 will optimize it and eliminate the conditionals. However, if you have lots of such code, then removing it would have two advantages: download size, and parsing time. When JavaScript code arrives in the browser, the engine has no choice but to look at every single byte of it at least briefly (if only to figure out which functions there are, and which parts of the code are in the top-level and must be executed immediately), and the fewer bytes there are, the more quickly that step completes. Parsing is fast, but parsing half as much is even faster!
Say we are inside an object that implements file handling. I want to write the code for easier readability.
Example of code where it can be difficult to tell the return type, especially when there are multiple nested function calls:
function create() {
return doCreateAction();
}
This example is more readable by introducing a clarifying variable:
function create() {
var fileHandle = doCreateAction();
return fileHandle;
}
In theory, the second version could perform identically because the compiler has to store the result from doCreateAction() temporarily anyway (probably inside some hiddenm, anonymous, short-lived temp variable). It this code any slower when assigning to a named variable?
I would say either they do optimize the variable out, or it's not worth bothering; and that in either case you have bigger fish to fry. :-) But there is an interesting aspect to this in relation to tail calls.
But first, in terms of simple performance: Empirically, this simplistic, synthetic test suggests that the performance of the function doesn't vary depending on whether there's a variable. Also note that a minifier will likely remove that variable for you before the JavaScript engine gets a look in, if you use a decent minifier.
Moving on to tail-calls: As you may know, as of ES2015 in strict mode the specificaton requires tail-call optimization (TCO), which means that when function A returns the result of calling function B, rather than having B return its result to A which then returns it to the caller, A passes control directly to B which then returns the result to the caller. This is more efficient in several ways (avoids creating another frame on the stack, avoids a jump).
Now, it may not matter because development of TCO in JavaScript engines is at least stalled if not dead. The V8 team developed an early version but abandoned it, SpiderMonkey doesn't have it either; as far as I know, only JavaScriptCore in Safari does TCO. But if I read the spec correctly (no mean feat), your first example has doCreateAction in the tail position and so can be optimized via TCO, but your second does not.
So there could be implications in that regard, if and when TCO is ever implemented widely and if, when it is, implementations go slightly beyond the spec for cases like this where clearly it is, in effect, a tail call.
I used to be fairly strict about using a variable in that situation for debugging purposes; moderately-recent versions of Chrome's devtools make it unnecessary for that purpose however (and of course, a minifier will remove it anyway): If you step into a return, you see the return value in the local scope list of variables. Of course, that's only useful if you're using Chrome's devtools (Firefox's, for instance, don't do this [yet?]).
We have a lot of objects in our code base that are name spaced to avoid collision.
Example : App.local.view.MyView...
In most of the places i have seen in the code base we use the full path to get a reference to the object and this is repeated multiple times within the same function.
Example :
function hello() {
App.local.view.MyView.render();
...
...
App.local.view.MyView.reset();
}
I wanted to understand if storing a reference to the object as below
var MyView = App.local.view.MyView;
would have any improvement in the performance. What makes me ask this question is form my understanding modern browsers like chrome do some optimization automatically for us behind the scenes.
It will be an improvement, but we're talking a completely negligible one.
It takes time to lookup a property of an object, but it's really quite fast.
If you're doing this for performance reasons, don't.
If you're doing this to make your code more readable/maintainable, then that's OK.
EDIT:
I created a benchmark to test this: Run the benchmark
var data = {a: {b: {c: {d: 1}}}};
var cache = data.a.b.c.d;
// uncached 901,326,988 ±1.03% fastest
// cached 879,568,962 ±0.95% 2% slower
// Chrome 41 on OSX 10.10
Well that's surprising !
Turns out it's faster to just call
data.a.b.c.d + 1
Instead of
cache + 1
I'm sure this varies based on implementation of JavaScript. Providing a specific reason for why this occurs will be left to other genii that dig around in js engine internals.
So with that in mind, my recommendations above stay the same:
If you're doing this for performance reasons, don't — it's actually slower.
If you're doing this to make your code more readable/maintainable, then that's OK — the performance cost is worth the value of more legible code.
This is implementation-specific and depends heavily on the underlying JavaScript engine.
For example, v8 engine (Chrome & maybe others) uses so-called hidden classes for JavaScript objects. This has the benefit that each object's property is known to be at a fixed offset in the memory and thus accessing an object's property is very fast.
On the other hand, some implementations (I only work with node.js so I do not have any particular browser references that use this method, but Firefox seems to be using this method - see below) may use dictionaries to map objects' properties to their memory locations. Dictionary lookups require more operations (more CPU cycles) and so they are somewhat slower.
In general, however, we are talking about extremely small difference.
To summarise, performance-wise this has almost no impact on your code performance. However, code style-wise, it can improve readability and maintainability of your code.
This jsperf (courtesy of #naomik) seems to support this - when run in Chrome, the difference is about 5%, whereas for Firefox it is a whopping 29%.
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'});
Are there any good tutorials on how to write fast, efficient code for v8 (specifically, for node.js)?
What structures should I avoid using? What are the idioms that v8 optimises well?
From my experience:
It does inlining
Function call overhead is minimal (inlining)
What is expensive is to pass huge strings to functions, since those need to be copied and from my experience V8 isn't always as smart as it could be in this case
Scope lookup is expensive (surprise)
Don't do tricks e.g. I have a binary encoder for JS Object, cranking out some extra performance with bit shifting there (instead of Math.floor) latest Crankshaft (yes alpha, but still) runs the code 30% slower
Don't use magic. eval, arguments.callee etc. Those pretty much kill any optimization since code can no longer be inlined
Some of the new ES5 stuff e.g. .bind() is really slow in V8 at the moment
Somehow new Object() and new Array() are a bit faster currently (MICROoptimization, unless you're writing some crazy encoder stick with {} and [])
My rules:
Write good code
Write working code
Write code that works in strict mode (support still has to land, but when it does further optimization can be applied by V8)
If you're an JS expert and your already applying all good practices to your code, there's hardly anything you can do to improve performance.
If you encounter performance issues:
Verify them
Change the code / algorithm
And as a last resort: Write a C++ extension (and watch every commit to ry/node on GitHub since nobody cares whether some internal changes break your build)
The docs give a great answer: http://code.google.com/apis/v8/design.html
Understanding V8 is a set of slides from nodecamp.eu and gives very some interesting tips. In particular, I found the notes on avoiding "dictionary mode" useful i.e. it helps if you keep the "shape" of objects constant and don't add arbitrary properties to them.
You should also run node with --crankshaft --trace-opt --trace-bailout (the --crankshaft is only needed on 64-bit platforms e.g. OS X) to see whether V8 is "bailing" on JITing certain functions. There is a ton of other trace options including --trace-gc and various other GC tracing, which can be useful for optimisation.
Let me know if you have any specific questions about the slides above as they're a bit concise. :-) They're not mine but I've done some research about the areas they cover.