SlideShare a Scribd company logo
1 of 54
Download to read offline
CAN YOU GET
HOW MUCH PERFORMANCE
OUT OF JAVASCRIPT?
Milano, Oct 11 2017
HOW MUCH PERFORMANCE
CAN YOU GET
OUT OF JAVASCRIPT?
Massimiliano Mantione
@M_a_s_s_i
The Mono JIT Compiler
The Unity Game Engine
The V8 Team in Google
Now CTO and Full Stack developer at Hyperfair
(Virtual Reality Platform)
THINGS I WORKED ON
Of course it does...
Please, ask a better question
DOES JAVASCRIPT PERFORMANCE
MATTER?
It depends on the application you are developing
Different question, please
DOES JAVASCRIPT PERFORMANCE
MATTER TO YOU?
Again, it depends
but we're getting there...
SHOULD I KNOW HOW TO WRITE
HIGH PERFORMANCE JAVASCRIPT?
now,
this is the correct question
SHOULD I KNOW THE
POTENTIAL
OF JAVASCRIPT CODE PERFORMANCE?
you cannot imagine anything new
and know if it is feasible
IF YOU DON'T KNOW IT
...a neural network working in real time inside a web
app?
How would you know if it would work?
WOULD YOU IMAGINE ADDING...
nd 25000 prime numbers
for x = 1 to in nity:
if x not divisible by any member of an initially empty
list of primes,
add x to the list until we have 25000 elements
A SIMPLE PROBLEM
How do I know?
Let's experiment!
HOW FAST WILL IT BE?
function Primes() {
this.prime_count = 0;
this.primes = new Array(25000);
this.getPrimeCount = function() { return this.prime_count; }
this.getPrime = function(i) { return this.primes[i]; }
this.addPrime = function(i) {
this.primes[this.prime_count++] = i;
}
this.isPrimeDivisible = function(candidate) {
for (var i = 1; i <= this.prime_count; ++i) {
if ((candidate % this.primes[i]) == 0) return true;
}
return false;
}
};
function main() {
p = new Primes();
var c = 1;
while (p.getPrimeCount() < 25000) {
if (!p.isPrimeDivisible(c)) {
p.addPrime(c);
}
c++;
}
print(p.getPrime(p.getPrimeCount()-1));
}
main();
THE CONTENDERS: JS
class Primes {
public:
int getPrimeCount() const { return prime_count; }
int getPrime(int i) const { return primes[i]; }
void addPrime(int i) { primes[prime_count++] = i; }
bool isDivisibe(int i, int by) { return (i % by) == 0; }
bool isPrimeDivisible(int candidate) {
for (int i = 1; i < prime_count; ++i) {
if (isDivisibe(candidate, primes[i])) return true;
}
return false;
}
private:
volatile int prime_count;
volatile int primes[25000];
};
int main() {
Primes p;
int c = 1;
while (p.getPrimeCount() < 25000) {
if (!p.isPrimeDivisible(c)) {
p.addPrime(c);
}
c++;
}
printf("%d
", p.getPrime(p.getPrimeCount()-1));
}
THE CONTENDERS: C++
LET'S
RACE!
C++ is almost 4 times faster than JavaScript
I guess that's not so bad, right?
Of course it is SO BAD!
OK, WE DID IT, NOW WE KNOW...
YOU DESERVE MORE
DON'T GIVE UP!
DEMAND FASTER!
3x?
30x?
300x?
How do we know?
HOW MUCH FASTER?
Know what to expect
Know how the VM executes and optimizes your code
Know how to inspect what is really going on
Know that you will never guess it right before
experimenting!
WE NEED TO BE PREPARED
V8
UNDERSTANDING HOW
OPTIMIZES JAVASCRIPT
Several steps
Interpreter: lots of branches to select the operation
Fast JIT: machine code with calls to (slow) generic
operations
JIT with type info: machine code with calls to speci c
operations
Optimizing JIT: as above but with compiler
optimizations
WHAT IS OPTIMIZED CODE?
No type info in the source code means no
optimizations
Type info could make JavaScript faster (like C++?)
V8 internally creates hidden classes for objects at
runtime
Objects with the same hidden class can use the
same optimized code
HIDDEN CLASSES
CODE
function Point(x, y) {
this.x = x;
this.y = y;
}
var p1 = new Point(11, 22);
var p2 = new Point(33, 44);
p2.z = 55;
Initialize all object members in constructor
functions
Always initialize object members in the same order
AVOID THE SPEED TRAP
Objects and numbers are very different
Javascript can mix them freely
V8 uses tagging: 1 bit in a pointer
Values can be objects, SMall Integers (SMI) or boxed
double
FAST NUMBERS
Prefer numeric values that can be represented as
31-bit signed integers
AVOID THE SPEED TRAP
Fast Elements: linear storage for compact key sets
Dictionary Elements: hash table storage otherwise
HANDLING LARGE AND SPARSE ARRAYS
CODE
a = new Array();
for (var b = 0; b < 10; b++) {
a[0] |= b; // Oh no!
}
a = new Array();
a[0] = 0;
for (var b = 0; b < 10; b++) {
a[0] |= b; // Much better! 2x faster.
}
Use contiguous keys starting at 0 for Arrays
Don't pre-allocate large Arrays (e.g. > 64K elements)
Don't delete elements in arrays, especially numeric
arrays
Don't load uninitialized or deleted elements
AVOID THE SPEED TRAP
Arrays of "pure doubles" are not slow
In general, hidden classes track array element types
[un]boxing causes hidden array class change
SPECIALIZED ARRAY ELEMENTS
CODE
// The bad way
var a = new Array();
a[0] = 77; // Allocates
a[1] = 88;
a[2] = 0.5; // Allocates, converts
a[3] = true; // Allocates, converts
// Hidden Classes for Elements - A Better Way
var a = [77, 88, 0.5, true];
Initialize using array literals for small xed-sized
arrays
Preallocate small arrays to correct size before using
them
Don't store non-numeric values (objects) in numeric
arrays
AVOID THE SPEED TRAP
Historically, V8 had two engines
"Full" compiler (fullGen) generated good code for any
JavaScript
Optimizing compiler (crankshaft) produced great
code for most JavaScript
FAST OR OPTIMIZING?
V8 gained two more engines
and lost the previous ones
Ignition, an interpreter for memory constrained
devices
Turbofan, an optimizing compiler even more
sophisticated than crankshaft
MORE ENGINES!
COMPILATION PIPELINE
An interpreter that starts executing code ASAP
Uses an internal bytecode representation
Initially assumes nothing about types
IGNITION
Handle types ef ciently in ignition
Type-dependent code for every operation
Validate type assumptions rst, then do work
ICs get better at runtime
Type information is used by turbofan
INLINE CACHES (IC)
// Consider this.primes
this.isPrimeDivisible = function(candidate) {
for (var i = 1; i <= this.prime_count; ++i) {
if (candidate % this.primes[i] == 0) return true;
}
return false;
}
JAVASCRIPT CODE
;; Computing this.primes
push [ebp+0x8] ;; Setting up stack frame
mov eax,[ebp+0xc]
mov edx,eax
mov ecx,0x50b155dd
call LoadIC_Initialize ;; this.primes
DUMB CODE STUB
;; Computing this.primes
;; ebx = this
cmp [ebx,<hidden class offset>],<cached hidden class>
jne <inline cache miss>
mov eax,[ebx, <primes offset>]
OPTIMAL CODE STUB
The optimizing compiler
Kicks in when the code is hot
Uses the type info collected by ICs
Optimizes like there's no tomorrow
TURBOFAN
TURBOFAN PIPELINE
Operations are monomorphic if the hidden class is
always the same
Otherwise they are polymorphic
Monomorphic is better than polymorphic
MEGAMORPHIC ATTACK!
CODE
function add(x, y) {
return x + y;
}
add(1, 2); // + in add is monomorphic
add("a", "b"); // + in add becomes polymorphic
Prefer monomorphic over polymorphic wherever
possible
Redux issues
(https://medium.com/@bmeurer/surprising-
polymorphism-in-react-applications-63015b50abc)
AVOID THE SPEED TRAP
V8 re-compiles hot functions with an optimizing
compiler
Type information makes code faster
Operations speculatively get inlined
Monomorphic calls and are also inlined
Inlining enables other optimizations
THE OPTIMIZING COMPILER
;; optimized code for candidate % this.primes[i]
cmp [edi+0xff],0x4920d181 ;; Is this a Primes object?
jnz 0x2a90a03c
mov eax,[edi+0xf] ;; Fetch this.primes
test eax,0x1 ;; Is primes a SMI ?
jz 0x2a90a050
cmp [eax+0xff],0x4920b001 ;; Is primes hidden class a packed SMI array?
mov ebx,[eax+0x7]
mov esi,[eax+0xb] ;; Load array length
sar esi,1 ;; Convert SMI length to int32
cmp ecx,esi ;; Check array bounds
jnc 0x2a90a06e
mov esi,[ebx+ecx*4+0x7] ;; Load element
sar esi,1 ;; Convert SMI element to int32
test esi,esi ;; mod (int32)
jz 0x2a90a078
...
cdq
idiv esi
In the past some constructs could not be optimized
(try-catch, with, generators...)
Now turbofan can optimize everything!
NO MORE BAILOUTS!
Optimizations are speculative
Usually, they pay off
AAARG... DEOPTIMIZATION!
throws away optimized code
resumes execution at the right place in ignition
reoptimization might be triggered again later, but for
the short term, execution slows down
DEOPTIMIZATION:
Avoid hidden class changes in functions after they
are optimized
Even if indirectly, Typescript and Flowtype help!
AVOID THE SPEED TRAP
Using the pro ler: --prof and --prof-process (nodejs)
Logging what gets optimized: --trace-opt
Detecting deoptimizations: --trace-deopt
Passing V8 options to Chrome: --js- ags="--trace-
opt --trace-deopt"
KNOW YOUR TOOLS
Ensure problem is JavaScript
Reduce to pure JavaScript (no DOM!)
Collect metrics
Locate bottleneck(s)
Fix problems(s)!
ARE YOU PREPARED?
LET'S MAKE IT
FASTER
THAT'S ALL...
QUESTIONS?

More Related Content

What's hot

Recipes to build Code Generators for Non-Xtext Models with Xtend
Recipes to build Code Generators for Non-Xtext Models with XtendRecipes to build Code Generators for Non-Xtext Models with Xtend
Recipes to build Code Generators for Non-Xtext Models with XtendKarsten Thoms
 
What To Expect From PHP7
What To Expect From PHP7What To Expect From PHP7
What To Expect From PHP7Codemotion
 
React Native Evening
React Native EveningReact Native Evening
React Native EveningTroy Miles
 
Functional solid
Functional solidFunctional solid
Functional solidMatt Stine
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Functional programming in Javascript
Functional programming in JavascriptFunctional programming in Javascript
Functional programming in JavascriptKnoldus Inc.
 
LINQ Inside
LINQ InsideLINQ Inside
LINQ Insidejeffz
 
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017Hardik Trivedi
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Arnaud Giuliani
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScriptTodd Anglin
 
Functional Javascript
Functional JavascriptFunctional Javascript
Functional Javascriptguest4d57e6
 
React Native One Day
React Native One DayReact Native One Day
React Native One DayTroy Miles
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoMuhammad Abdullah
 
GR8Conf 2011: GPars
GR8Conf 2011: GParsGR8Conf 2011: GPars
GR8Conf 2011: GParsGR8Conf
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is hereSebastiano Armeli
 

What's hot (20)

Recipes to build Code Generators for Non-Xtext Models with Xtend
Recipes to build Code Generators for Non-Xtext Models with XtendRecipes to build Code Generators for Non-Xtext Models with Xtend
Recipes to build Code Generators for Non-Xtext Models with Xtend
 
What To Expect From PHP7
What To Expect From PHP7What To Expect From PHP7
What To Expect From PHP7
 
React Native Evening
React Native EveningReact Native Evening
React Native Evening
 
Functional solid
Functional solidFunctional solid
Functional solid
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Functional programming in Javascript
Functional programming in JavascriptFunctional programming in Javascript
Functional programming in Javascript
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
LINQ Inside
LINQ InsideLINQ Inside
LINQ Inside
 
Introduction to Elm
Introduction to ElmIntroduction to Elm
Introduction to Elm
 
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
 
Functional Javascript
Functional JavascriptFunctional Javascript
Functional Javascript
 
React Native One Day
React Native One DayReact Native One Day
React Native One Day
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 
Elm kyivfprog 2015
Elm kyivfprog 2015Elm kyivfprog 2015
Elm kyivfprog 2015
 
The Joy Of Ruby
The Joy Of RubyThe Joy Of Ruby
The Joy Of Ruby
 
GR8Conf 2011: GPars
GR8Conf 2011: GParsGR8Conf 2011: GPars
GR8Conf 2011: GPars
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 

Similar to How much performance can you get out of Javascript? - Massimiliano Mantione - Codemotion Milan 2017

12 Monkeys Inside JS Engine
12 Monkeys Inside JS Engine12 Monkeys Inside JS Engine
12 Monkeys Inside JS EngineChengHui Weng
 
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?", Yevhen TatarynovFwdays
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningCarol McDonald
 
How do you create a programming language for the JVM?
How do you create a programming language for the JVM?How do you create a programming language for the JVM?
How do you create a programming language for the JVM?Federico Tomassetti
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and BeyondComicSansMS
 
Automate ml workflow_transmogrif_ai-_chetan_khatri_berlin-scala
Automate ml workflow_transmogrif_ai-_chetan_khatri_berlin-scalaAutomate ml workflow_transmogrif_ai-_chetan_khatri_berlin-scala
Automate ml workflow_transmogrif_ai-_chetan_khatri_berlin-scalaChetan Khatri
 
Optimization in the world of 64-bit errors
Optimization  in the world of 64-bit errorsOptimization  in the world of 64-bit errors
Optimization in the world of 64-bit errorsPVS-Studio
 
JS Responsibilities
JS ResponsibilitiesJS Responsibilities
JS ResponsibilitiesBrendan Eich
 
Intel JIT Talk
Intel JIT TalkIntel JIT Talk
Intel JIT Talkiamdvander
 
Static analysis of C++ source code
Static analysis of C++ source codeStatic analysis of C++ source code
Static analysis of C++ source codePVS-Studio
 
Static analysis of C++ source code
Static analysis of C++ source codeStatic analysis of C++ source code
Static analysis of C++ source codeAndrey Karpov
 
Headache from using mathematical software
Headache from using mathematical softwareHeadache from using mathematical software
Headache from using mathematical softwarePVS-Studio
 
Java Jit. Compilation and optimization by Andrey Kovalenko
Java Jit. Compilation and optimization by Andrey KovalenkoJava Jit. Compilation and optimization by Andrey Kovalenko
Java Jit. Compilation and optimization by Andrey KovalenkoValeriia Maliarenko
 
C interview questions
C interview questionsC interview questions
C interview questionsSoba Arjun
 
Pure Functions and Immutable Objects
Pure Functions and Immutable ObjectsPure Functions and Immutable Objects
Pure Functions and Immutable ObjectsVictor Rentea
 

Similar to How much performance can you get out of Javascript? - Massimiliano Mantione - Codemotion Milan 2017 (20)

12 Monkeys Inside JS Engine
12 Monkeys Inside JS Engine12 Monkeys Inside JS Engine
12 Monkeys Inside JS Engine
 
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
 
How do you create a programming language for the JVM?
How do you create a programming language for the JVM?How do you create a programming language for the JVM?
How do you create a programming language for the JVM?
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and Beyond
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
Quiz 9
Quiz 9Quiz 9
Quiz 9
 
C++ Homework Help
C++ Homework HelpC++ Homework Help
C++ Homework Help
 
Automate ml workflow_transmogrif_ai-_chetan_khatri_berlin-scala
Automate ml workflow_transmogrif_ai-_chetan_khatri_berlin-scalaAutomate ml workflow_transmogrif_ai-_chetan_khatri_berlin-scala
Automate ml workflow_transmogrif_ai-_chetan_khatri_berlin-scala
 
Optimization in the world of 64-bit errors
Optimization  in the world of 64-bit errorsOptimization  in the world of 64-bit errors
Optimization in the world of 64-bit errors
 
JS Responsibilities
JS ResponsibilitiesJS Responsibilities
JS Responsibilities
 
Functional programming in C++
Functional programming in C++Functional programming in C++
Functional programming in C++
 
Intel JIT Talk
Intel JIT TalkIntel JIT Talk
Intel JIT Talk
 
Static analysis of C++ source code
Static analysis of C++ source codeStatic analysis of C++ source code
Static analysis of C++ source code
 
Static analysis of C++ source code
Static analysis of C++ source codeStatic analysis of C++ source code
Static analysis of C++ source code
 
Headache from using mathematical software
Headache from using mathematical softwareHeadache from using mathematical software
Headache from using mathematical software
 
Java Jit. Compilation and optimization by Andrey Kovalenko
Java Jit. Compilation and optimization by Andrey KovalenkoJava Jit. Compilation and optimization by Andrey Kovalenko
Java Jit. Compilation and optimization by Andrey Kovalenko
 
C interview questions
C interview questionsC interview questions
C interview questions
 
Pure Functions and Immutable Objects
Pure Functions and Immutable ObjectsPure Functions and Immutable Objects
Pure Functions and Immutable Objects
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance Tuning
 

More from Codemotion

Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...Codemotion
 
Pompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending storyPompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending storyCodemotion
 
Pastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storiaPastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storiaCodemotion
 
Pennisi - Essere Richard Altwasser
Pennisi - Essere Richard AltwasserPennisi - Essere Richard Altwasser
Pennisi - Essere Richard AltwasserCodemotion
 
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...Codemotion
 
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019Codemotion
 
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019Codemotion
 
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 - Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 - Codemotion
 
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...Codemotion
 
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...Codemotion
 
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...Codemotion
 
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...Codemotion
 
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019Codemotion
 
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019Codemotion
 
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019Codemotion
 
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...Codemotion
 
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...Codemotion
 
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019Codemotion
 
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019Codemotion
 
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019Codemotion
 

More from Codemotion (20)

Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
 
Pompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending storyPompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending story
 
Pastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storiaPastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storia
 
Pennisi - Essere Richard Altwasser
Pennisi - Essere Richard AltwasserPennisi - Essere Richard Altwasser
Pennisi - Essere Richard Altwasser
 
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
 
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
 
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
 
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 - Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
 
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
 
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
 
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
 
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
 
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
 
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
 
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
 
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
 
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
 
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
 
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
 
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
 

Recently uploaded

Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 

Recently uploaded (20)

Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

How much performance can you get out of Javascript? - Massimiliano Mantione - Codemotion Milan 2017

  • 1. CAN YOU GET HOW MUCH PERFORMANCE OUT OF JAVASCRIPT?
  • 2. Milano, Oct 11 2017 HOW MUCH PERFORMANCE CAN YOU GET OUT OF JAVASCRIPT? Massimiliano Mantione @M_a_s_s_i
  • 3. The Mono JIT Compiler The Unity Game Engine The V8 Team in Google Now CTO and Full Stack developer at Hyperfair (Virtual Reality Platform) THINGS I WORKED ON
  • 4. Of course it does... Please, ask a better question DOES JAVASCRIPT PERFORMANCE MATTER?
  • 5. It depends on the application you are developing Different question, please DOES JAVASCRIPT PERFORMANCE MATTER TO YOU?
  • 6. Again, it depends but we're getting there... SHOULD I KNOW HOW TO WRITE HIGH PERFORMANCE JAVASCRIPT?
  • 7. now, this is the correct question SHOULD I KNOW THE POTENTIAL OF JAVASCRIPT CODE PERFORMANCE?
  • 8. you cannot imagine anything new and know if it is feasible IF YOU DON'T KNOW IT
  • 9. ...a neural network working in real time inside a web app? How would you know if it would work? WOULD YOU IMAGINE ADDING...
  • 10. nd 25000 prime numbers for x = 1 to in nity: if x not divisible by any member of an initially empty list of primes, add x to the list until we have 25000 elements A SIMPLE PROBLEM
  • 11. How do I know? Let's experiment! HOW FAST WILL IT BE?
  • 12. function Primes() { this.prime_count = 0; this.primes = new Array(25000); this.getPrimeCount = function() { return this.prime_count; } this.getPrime = function(i) { return this.primes[i]; } this.addPrime = function(i) { this.primes[this.prime_count++] = i; } this.isPrimeDivisible = function(candidate) { for (var i = 1; i <= this.prime_count; ++i) { if ((candidate % this.primes[i]) == 0) return true; } return false; } }; function main() { p = new Primes(); var c = 1; while (p.getPrimeCount() < 25000) { if (!p.isPrimeDivisible(c)) { p.addPrime(c); } c++; } print(p.getPrime(p.getPrimeCount()-1)); } main(); THE CONTENDERS: JS
  • 13. class Primes { public: int getPrimeCount() const { return prime_count; } int getPrime(int i) const { return primes[i]; } void addPrime(int i) { primes[prime_count++] = i; } bool isDivisibe(int i, int by) { return (i % by) == 0; } bool isPrimeDivisible(int candidate) { for (int i = 1; i < prime_count; ++i) { if (isDivisibe(candidate, primes[i])) return true; } return false; } private: volatile int prime_count; volatile int primes[25000]; }; int main() { Primes p; int c = 1; while (p.getPrimeCount() < 25000) { if (!p.isPrimeDivisible(c)) { p.addPrime(c); } c++; } printf("%d ", p.getPrime(p.getPrimeCount()-1)); } THE CONTENDERS: C++
  • 15. C++ is almost 4 times faster than JavaScript I guess that's not so bad, right? Of course it is SO BAD! OK, WE DID IT, NOW WE KNOW...
  • 16. YOU DESERVE MORE DON'T GIVE UP! DEMAND FASTER!
  • 17. 3x? 30x? 300x? How do we know? HOW MUCH FASTER?
  • 18. Know what to expect Know how the VM executes and optimizes your code Know how to inspect what is really going on Know that you will never guess it right before experimenting! WE NEED TO BE PREPARED
  • 20. Several steps Interpreter: lots of branches to select the operation Fast JIT: machine code with calls to (slow) generic operations JIT with type info: machine code with calls to speci c operations Optimizing JIT: as above but with compiler optimizations WHAT IS OPTIMIZED CODE?
  • 21. No type info in the source code means no optimizations Type info could make JavaScript faster (like C++?) V8 internally creates hidden classes for objects at runtime Objects with the same hidden class can use the same optimized code HIDDEN CLASSES
  • 22. CODE function Point(x, y) { this.x = x; this.y = y; } var p1 = new Point(11, 22); var p2 = new Point(33, 44); p2.z = 55;
  • 23. Initialize all object members in constructor functions Always initialize object members in the same order AVOID THE SPEED TRAP
  • 24. Objects and numbers are very different Javascript can mix them freely V8 uses tagging: 1 bit in a pointer Values can be objects, SMall Integers (SMI) or boxed double FAST NUMBERS
  • 25. Prefer numeric values that can be represented as 31-bit signed integers AVOID THE SPEED TRAP
  • 26. Fast Elements: linear storage for compact key sets Dictionary Elements: hash table storage otherwise HANDLING LARGE AND SPARSE ARRAYS
  • 27. CODE a = new Array(); for (var b = 0; b < 10; b++) { a[0] |= b; // Oh no! } a = new Array(); a[0] = 0; for (var b = 0; b < 10; b++) { a[0] |= b; // Much better! 2x faster. }
  • 28. Use contiguous keys starting at 0 for Arrays Don't pre-allocate large Arrays (e.g. > 64K elements) Don't delete elements in arrays, especially numeric arrays Don't load uninitialized or deleted elements AVOID THE SPEED TRAP
  • 29. Arrays of "pure doubles" are not slow In general, hidden classes track array element types [un]boxing causes hidden array class change SPECIALIZED ARRAY ELEMENTS
  • 30. CODE // The bad way var a = new Array(); a[0] = 77; // Allocates a[1] = 88; a[2] = 0.5; // Allocates, converts a[3] = true; // Allocates, converts // Hidden Classes for Elements - A Better Way var a = [77, 88, 0.5, true];
  • 31. Initialize using array literals for small xed-sized arrays Preallocate small arrays to correct size before using them Don't store non-numeric values (objects) in numeric arrays AVOID THE SPEED TRAP
  • 32. Historically, V8 had two engines "Full" compiler (fullGen) generated good code for any JavaScript Optimizing compiler (crankshaft) produced great code for most JavaScript FAST OR OPTIMIZING?
  • 33. V8 gained two more engines and lost the previous ones Ignition, an interpreter for memory constrained devices Turbofan, an optimizing compiler even more sophisticated than crankshaft MORE ENGINES!
  • 35. An interpreter that starts executing code ASAP Uses an internal bytecode representation Initially assumes nothing about types IGNITION
  • 36. Handle types ef ciently in ignition Type-dependent code for every operation Validate type assumptions rst, then do work ICs get better at runtime Type information is used by turbofan INLINE CACHES (IC)
  • 37. // Consider this.primes this.isPrimeDivisible = function(candidate) { for (var i = 1; i <= this.prime_count; ++i) { if (candidate % this.primes[i] == 0) return true; } return false; } JAVASCRIPT CODE
  • 38. ;; Computing this.primes push [ebp+0x8] ;; Setting up stack frame mov eax,[ebp+0xc] mov edx,eax mov ecx,0x50b155dd call LoadIC_Initialize ;; this.primes DUMB CODE STUB
  • 39. ;; Computing this.primes ;; ebx = this cmp [ebx,<hidden class offset>],<cached hidden class> jne <inline cache miss> mov eax,[ebx, <primes offset>] OPTIMAL CODE STUB
  • 40. The optimizing compiler Kicks in when the code is hot Uses the type info collected by ICs Optimizes like there's no tomorrow TURBOFAN
  • 42. Operations are monomorphic if the hidden class is always the same Otherwise they are polymorphic Monomorphic is better than polymorphic MEGAMORPHIC ATTACK!
  • 43. CODE function add(x, y) { return x + y; } add(1, 2); // + in add is monomorphic add("a", "b"); // + in add becomes polymorphic
  • 44. Prefer monomorphic over polymorphic wherever possible Redux issues (https://medium.com/@bmeurer/surprising- polymorphism-in-react-applications-63015b50abc) AVOID THE SPEED TRAP
  • 45. V8 re-compiles hot functions with an optimizing compiler Type information makes code faster Operations speculatively get inlined Monomorphic calls and are also inlined Inlining enables other optimizations THE OPTIMIZING COMPILER
  • 46. ;; optimized code for candidate % this.primes[i] cmp [edi+0xff],0x4920d181 ;; Is this a Primes object? jnz 0x2a90a03c mov eax,[edi+0xf] ;; Fetch this.primes test eax,0x1 ;; Is primes a SMI ? jz 0x2a90a050 cmp [eax+0xff],0x4920b001 ;; Is primes hidden class a packed SMI array? mov ebx,[eax+0x7] mov esi,[eax+0xb] ;; Load array length sar esi,1 ;; Convert SMI length to int32 cmp ecx,esi ;; Check array bounds jnc 0x2a90a06e mov esi,[ebx+ecx*4+0x7] ;; Load element sar esi,1 ;; Convert SMI element to int32 test esi,esi ;; mod (int32) jz 0x2a90a078 ... cdq idiv esi
  • 47. In the past some constructs could not be optimized (try-catch, with, generators...) Now turbofan can optimize everything! NO MORE BAILOUTS!
  • 48. Optimizations are speculative Usually, they pay off AAARG... DEOPTIMIZATION!
  • 49. throws away optimized code resumes execution at the right place in ignition reoptimization might be triggered again later, but for the short term, execution slows down DEOPTIMIZATION:
  • 50. Avoid hidden class changes in functions after they are optimized Even if indirectly, Typescript and Flowtype help! AVOID THE SPEED TRAP
  • 51. Using the pro ler: --prof and --prof-process (nodejs) Logging what gets optimized: --trace-opt Detecting deoptimizations: --trace-deopt Passing V8 options to Chrome: --js- ags="--trace- opt --trace-deopt" KNOW YOUR TOOLS
  • 52. Ensure problem is JavaScript Reduce to pure JavaScript (no DOM!) Collect metrics Locate bottleneck(s) Fix problems(s)! ARE YOU PREPARED?