High Performance JS in V8
Peter Marshall - V8 Engineer
Chrome
Chrome
Why do we care?
Chrome
What is an Engine, Anyway?
“Alice”
“Hello, Alice”
greeter.exe
Chrome
What is an Engine, Anyway?
“2 + 2”
“4”
Chrome
What is an Engine, Anyway?
Chrome
Why is JS so tricky?
Chrome
“Speculative Optimization a.k.a Guessing”
function updateData(node, user) {� node.userName = user.first + user.last;�}
Chrome
“Speculative Optimization a.k.a Guessing”
function updateData(node, user) {� node.userName = user.first + user.last;�}
Property Load
Property Load
Property Store
Plus Operation
Chrome
Feedback and Deoptimization
function updateData(node, user) {� node.userName = user.first + user.last;�}
String
String
String
String Concat
Chrome
Chrome
How it was: Crankshaft
Chrome
The Old V8 Architecture
Parser
“2 + 2”
2
2
+
AST
Source�Code
Fullcode�Gen
Crankshaft
ASM Code
Addq 0x2,0x2
…�Movq rax, rbx
x64, ARM, etc. (9 total!)
Baseline Compiler
Optimizing Compiler
“4”
Output
C++ Runtime
Chrome
Problems
Crankshaft was starting to show its age:
Chrome
“Communication” Process
“You’re holding it wrong”
“This is how we’re holding it”
Chrome
Crankshaft Performance Advice
Chrome
CrankshaftScript 1
“/* This implementation of checkIsHttpToken() loops over the string instead of using a regular expression since the former is up to 180% faster with v8 4.9 */”
var validTokens = [0, 1, 0, … /*256 length */ , 0];
function checkIsHttpToken(val) {
if (!validTokens[val.charCodeAt(0)])
return false;
if (val.length < 2)
return true;
if (!validTokens[val.charCodeAt(1)])
return false;
if (val.length < 3)
return true;
if (!validTokens[val.charCodeAt(2)])
return false;
for (var i = 3; i < val.length; ++i) {
if (!validTokens[val.charCodeAt(i)])
return false;
}
return true;
}
Chrome
CrankshaftScript 1
const token = /^[a-zA-Z0-9_!#$%&'*+.^`|~-]+$/;
function checkIsHttpToken(val) {
return typeof val === 'string' && token.test(val);
}
Chrome
CrankshaftScript 2
function foo(x) {
try {
return bar(x);
} catch (e) {
return 0;
}
}
function bar(x) {
return x.thingThatMightThrow();
}
V8 5.1
V8 6.0
1.27x
1.00x
(19x)
Chrome
Chrome
Ignition + Turbofan
Chrome
The New V8 Architecture
Parser
“2 + 2”
2
2
+
AST
Source�Code
Bytecode�Generator
Turbofan
ASM Code
Addq 0x2,0x2
…�Movq rax, rbx
x64, ARM, etc. (9 total!)
Optimizing Compiler
“4”
Output
Ignition
C++ Runtime
Interpreter
Chrome
Advantages of the New World
Chrome
Real World Performance Results
Chrome
Fast JS for Turbofan
What would “TurbofanScript” look like?
Chrome
Changing JS Ecosystem
Chrome
Transpilation and Frameworks
Performance:
�Compatibility
Sanity
Chrome
What About ES6 Features?
ES6:
Math.max(...[1, 2, 3]);
ES5:
Math.max.apply(Math, [1, 2, 3]);
19x
Chrome
420kB
Code shipped to the average website
Chrome
15-20%
Total V8 time taken in parsing
Chrome
Takeaways
Chrome
Thanks!
petermarshall@google.com
Chrome