SlideShare a Scribd company logo
V8 + libuv = Node.js
Under the hood
Юрий Шевцов
Все познается в
сравнении
int func2(int arg1, char *arg2) {
char str[100];
/* some other expressions */
}
int func1() {
int foo = 0;
int bar = 3;
char* buzz = malloc(5);
func2(foo, buzz);
}
char* buzz (stack slot with
address)
int bar = 3
int foo = 3
Return address
Params of func1
Stack
int func2(int arg1, char *arg2) {
char str[100];
/* some other expressions */
}
int func1() {
int foo = 0;
int bar = 3;
char* buzz = malloc(5);
func2(foo, buzz);
}
str[99]
str[1] … str[98]
str[0];
Return address (line 10)
arg2 = buzz
arg1 = foo = 3
Data of func1
Stack
Stackframe
● Arguments
● Local variables
● Return address
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Everything is object on the Heap
for (let i = 0; i < 42; i++) {}
foo[1]
foo[231]
Except SMI (Small integers)
2 42
570
200
Tagged pointer
32nd bit 1st bit
Data bits
T == 0 - SMI
T == 1 - Pointer T X X X X X ... X X X X X X
Object
representation
Hashtable
VS
Optimised View
Closer look
JSObject
Map
Extra Properties
Elements
Property “a”
Property “b”
FixedArray
Map
Length
Property “c”
Property “d”
FixedArray
Map
Length
Property “1”
Property “2”
Property “3”
32 Slots and extra properties
1. Object gets 32 slots
2. V8 trims unused slots later
3. Extra properties go separately
Elements
● Keys are array indices
● Elements may be represented as simple
array
● Unbox values, if numbers only
Map a.k.a Hidden Class
● Stores object layout ({ property: offset })
● Assignment order matters
● New map created for each object change
● Allows fast property lookup
Maps creation
function Foo(bar, buzz) {
this.bar = bar;
this.buzz = buzz;
}
const foo1 = new Foo(1, 2);
const foo2 = new Foo(3, 4);
foo1.some = 5;
{ } - C0
{ bar } - C1
{ bar, buzz } - C2
{ bar, buzz, some } - C3
Inline caching
Heap Structure
New-space Old-space And more...
Garbage collection
Scavenge | Mark & sweep
Mark
Compact
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Asynchronicity
<script type="text/javascript">
setTimeout(() => console.log(1));
Promise.resolve().then(() => console.log(2));
</script>
Two standards
VS
ECMAScript WHATVG
Task types
Tasks:
setTimeout, requestAnimationFrame, I/O, UI
rendering
Microtasks:
Promises, process.nextTick, MutationObserver
Event loop algorithm
1. Run task till completion
2. Run microtasks
3. Run microtask scheduled by another
microtask
Correct answer
2
1
Hint: running script is also a task
V8 compilers
Before
Full-codegen - generates unoptimized machine code
Crankshaft - optimizes hot functions
V8 compilers
Ignition - generates bytecode
Turbofan - optimizes, using Sea-of-Nodes graph
interpreter + compiler
V8 is a library
Bare V8 runs scripts
Isolate* isolate = Isolate::New()
Local<Context> context = Context::New(isolate)
Local<String> source = String::New(isolate, "'Hello , World!'")
Local<Script> script = Script::Compile(context, source)
Local<Value> result = script->Run(context)
V8 API terminology
Isolate - instance of V8 VM
Context - holds pristine copy of global object
Local<?> - handle for JS object in heap
Two templates
Functions
Objects
Function Template
void LogCallback(FunctionCallbackInfo<Value>& args) {}
global->Set("log", FunctionTemplate::New(isolate, LogCallback));
Object Template
Interceptors Accessors
Example
global_templ->SetAccessor("foo", XGetter, XSetter);
void XGetter(Local<String> property) {
info.GetReturnValue().Set(x);
}
void XSetter(Local<String> property, Local<Value> value) {
x = value->Int32Value();
}
Local<ObjectTemplate> global = ObjectTemplate::New(isolate);
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
do {
uv__update_time(loop);
uv__run_timers(loop);
uv__run_idle(loop);
uv__run_prepare(loop);
uv__io_poll(loop, timeout);
uv__run_check(loop);
uv__run_closing_handles(loop);
} while (uv__loop_alive(loop))
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Node.js is...
● V8 initializer
● libuv wrapper
● Module loader
Your module is a function
NativeModule.wrap = function(script) {
return NativeModule.wrapper[0]+script+NativeModule.wrapper[1];
};
NativeModule.wrapper = [
'(function (exports, require, module, __filename, __dirname) { ',
'n});'
];
Native modules
NAN vs N-API
Спасибо за внимание!

More Related Content

PDF
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
PDF
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
PDF
Understanding the nodejs event loop
PPT
PDF
Faster Python, FOSDEM
PDF
Data structure programs in c++
PDF
Kirk Shoop, Reactive programming in C++
PDF
Python opcodes
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Understanding the nodejs event loop
Faster Python, FOSDEM
Data structure programs in c++
Kirk Shoop, Reactive programming in C++
Python opcodes

What's hot (20)

PDF
All I know about rsc.io/c2go
PPTX
TCO in Python via bytecode manipulation.
PDF
GoでKVSを書けるのか
PDF
D vs OWKN Language at LLnagoya
PDF
The Big Three
PPTX
PVS-Studio team experience: checking various open source projects, or mistake...
PPT
Евгений Крутько, Многопоточные вычисления, современный подход.
PPT
NS2: Binding C++ and OTcl variables
PDF
"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...
PDF
Bytes in the Machine: Inside the CPython interpreter
PPTX
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
PDF
Алексей Кутумов, Coroutines everywhere
PDF
PyCon KR 2019 sprint - RustPython by example
PDF
When RV Meets CEP (RV 2016 Tutorial)
PDF
Protocol handler in Gecko
PDF
Rcpp11 useR2014
PDF
Project_Euler_No_104_Pandigital_Fibonacci_ends
 
PDF
C# Assignmet Help
PPT
C++totural file
PDF
3 rd animation
All I know about rsc.io/c2go
TCO in Python via bytecode manipulation.
GoでKVSを書けるのか
D vs OWKN Language at LLnagoya
The Big Three
PVS-Studio team experience: checking various open source projects, or mistake...
Евгений Крутько, Многопоточные вычисления, современный подход.
NS2: Binding C++ and OTcl variables
"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...
Bytes in the Machine: Inside the CPython interpreter
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
Алексей Кутумов, Coroutines everywhere
PyCon KR 2019 sprint - RustPython by example
When RV Meets CEP (RV 2016 Tutorial)
Protocol handler in Gecko
Rcpp11 useR2014
Project_Euler_No_104_Pandigital_Fibonacci_ends
 
C# Assignmet Help
C++totural file
3 rd animation
Ad

Similar to Yurii Shevtsov "V8 + libuv = Node.js. Under the hood" (20)

PPTX
Node.js - Advanced Basics
PDF
Advanced Node.JS Meetup
PDF
Whose Stack Is It Anyway?
PDF
ITCamp 2017 - Raffaele Rialdi - A Deep Dive Into Bridging Node-js with .NET Core
PDF
Writing native bindings to node.js in C++
PPTX
OLD VERSION - Understanding the V8 Runtime to Maximize Application Performance
PDF
Vaugham Hong - Embedding JavaScript V8
PDF
Raffaele Rialdi
PPTX
Node.js behind: V8 and its optimizations
PDF
Run-time of Node.js : V8 JavaScript Engine
PDF
How much performance can you get out of Javascript? - Massimiliano Mantione -...
PPTX
Understanding the v8 runtime to maximize application performance
PPTX
NodeJS
PDF
JS Fest 2019. Артур Торосян. V8 - взгляд на асинхронность и работу с ОС изнутри
PPTX
Run Node Run
PPTX
All you need to know about the JavaScript event loop
PPTX
Garbage collectors and Memory Leaks in Nodejs - V8
PPTX
Google V8 engine
PDF
JS Responsibilities
PDF
Extending Node.js using C++
Node.js - Advanced Basics
Advanced Node.JS Meetup
Whose Stack Is It Anyway?
ITCamp 2017 - Raffaele Rialdi - A Deep Dive Into Bridging Node-js with .NET Core
Writing native bindings to node.js in C++
OLD VERSION - Understanding the V8 Runtime to Maximize Application Performance
Vaugham Hong - Embedding JavaScript V8
Raffaele Rialdi
Node.js behind: V8 and its optimizations
Run-time of Node.js : V8 JavaScript Engine
How much performance can you get out of Javascript? - Massimiliano Mantione -...
Understanding the v8 runtime to maximize application performance
NodeJS
JS Fest 2019. Артур Торосян. V8 - взгляд на асинхронность и работу с ОС изнутри
Run Node Run
All you need to know about the JavaScript event loop
Garbage collectors and Memory Leaks in Nodejs - V8
Google V8 engine
JS Responsibilities
Extending Node.js using C++
Ad

More from OdessaJS Conf (20)

PPTX
'GraphQL Schema Design' by Borys Mohyla. OdessaJS'2021
PDF
'How i came up with my talk' by Yurii Artiukh. OdessaJS'2021
PDF
"Is there life in react without redux" by Babich Sergiy. OdessaJS'2021
PPTX
Олексій Павленко. CONTRACT PROTECTION ON THE FRONTEND SIDE: HOW TO ORGANIZE R...
PPTX
Андрій Троян. Розробка мікросервісів з NestJS. OdessaJS'2021
PPTX
Олексій Гончар "Використання Electron в розробці корпоративної відео-мессeндж...
PDF
Максим Климишин "Що такого особливого у пропозиції вартості шаблону Micro Fro...
PDF
Павло Галушко. GOOD CODE MYTHS. OdessaJS'2021
PPTX
"NODEJS & GRAPHQL COOKBOOK. LET’S TALK ABOUT MICRO-SERVICES" by Антон Чередні...
PPTX
'BUILDING ANGULAR APPS WITH NX' by Anastasia Necheporenko
PPTX
'IS THERE JAVASCRIPT ON SWAGGER PLUGINS?' by Dmytro Gusev
PPTX
'ETHEREUM SMART CONTRACTS ON JS' by Yaroslav Dvorovenko
PPTX
'GOLANG USAGE IN DEVELOPMENT OF NODE.JS APPLICATIONS (NODE.JS: IN GO WE TRUST...
PPTX
'MICROFRONTENDS WITH REACT' by Liliia Karpenko
PDF
'Web performance metrics' BY ROMAN SAVITSKYI at OdessaJS'2020
PDF
'STORY OF ANOTHER ANIMATION' by YURII ARTYUKH at OdessaJS'2020
PDF
'JavaScript was invented in Odessa' by DMITRIY GUSEV at OdessaJS'2020
PDF
'Why svelte' by BORYS MOHYLA at OdessaJS'2020
PDF
'Effective node.js development' by Viktor Turskyi at OdessaJS'2020
PDF
'Tensorflow.js in real life' by Pavlo Galushko at OdessaJS'2020
'GraphQL Schema Design' by Borys Mohyla. OdessaJS'2021
'How i came up with my talk' by Yurii Artiukh. OdessaJS'2021
"Is there life in react without redux" by Babich Sergiy. OdessaJS'2021
Олексій Павленко. CONTRACT PROTECTION ON THE FRONTEND SIDE: HOW TO ORGANIZE R...
Андрій Троян. Розробка мікросервісів з NestJS. OdessaJS'2021
Олексій Гончар "Використання Electron в розробці корпоративної відео-мессeндж...
Максим Климишин "Що такого особливого у пропозиції вартості шаблону Micro Fro...
Павло Галушко. GOOD CODE MYTHS. OdessaJS'2021
"NODEJS & GRAPHQL COOKBOOK. LET’S TALK ABOUT MICRO-SERVICES" by Антон Чередні...
'BUILDING ANGULAR APPS WITH NX' by Anastasia Necheporenko
'IS THERE JAVASCRIPT ON SWAGGER PLUGINS?' by Dmytro Gusev
'ETHEREUM SMART CONTRACTS ON JS' by Yaroslav Dvorovenko
'GOLANG USAGE IN DEVELOPMENT OF NODE.JS APPLICATIONS (NODE.JS: IN GO WE TRUST...
'MICROFRONTENDS WITH REACT' by Liliia Karpenko
'Web performance metrics' BY ROMAN SAVITSKYI at OdessaJS'2020
'STORY OF ANOTHER ANIMATION' by YURII ARTYUKH at OdessaJS'2020
'JavaScript was invented in Odessa' by DMITRIY GUSEV at OdessaJS'2020
'Why svelte' by BORYS MOHYLA at OdessaJS'2020
'Effective node.js development' by Viktor Turskyi at OdessaJS'2020
'Tensorflow.js in real life' by Pavlo Galushko at OdessaJS'2020

Recently uploaded (20)

PDF
Paper PDF World Game (s) Great Redesign.pdf
PPTX
Internet___Basics___Styled_ presentation
PDF
SASE Traffic Flow - ZTNA Connector-1.pdf
PPT
Design_with_Watersergyerge45hrbgre4top (1).ppt
PDF
An introduction to the IFRS (ISSB) Stndards.pdf
PPT
tcp ip networks nd ip layering assotred slides
PPTX
CHE NAA, , b,mn,mblblblbljb jb jlb ,j , ,C PPT.pptx
PDF
Automated vs Manual WooCommerce to Shopify Migration_ Pros & Cons.pdf
PPTX
Introuction about WHO-FIC in ICD-10.pptx
PPTX
522797556-Unit-2-Temperature-measurement-1-1.pptx
PPTX
innovation process that make everything different.pptx
PPTX
Funds Management Learning Material for Beg
PDF
💰 𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓 💰
PPTX
artificial intelligence overview of it and more
PDF
Testing WebRTC applications at scale.pdf
PDF
WebRTC in SignalWire - troubleshooting media negotiation
DOCX
Unit-3 cyber security network security of internet system
PDF
The Internet -By the Numbers, Sri Lanka Edition
PDF
APNIC Update, presented at PHNOG 2025 by Shane Hermoso
PPTX
Job_Card_System_Styled_lorem_ipsum_.pptx
Paper PDF World Game (s) Great Redesign.pdf
Internet___Basics___Styled_ presentation
SASE Traffic Flow - ZTNA Connector-1.pdf
Design_with_Watersergyerge45hrbgre4top (1).ppt
An introduction to the IFRS (ISSB) Stndards.pdf
tcp ip networks nd ip layering assotred slides
CHE NAA, , b,mn,mblblblbljb jb jlb ,j , ,C PPT.pptx
Automated vs Manual WooCommerce to Shopify Migration_ Pros & Cons.pdf
Introuction about WHO-FIC in ICD-10.pptx
522797556-Unit-2-Temperature-measurement-1-1.pptx
innovation process that make everything different.pptx
Funds Management Learning Material for Beg
💰 𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓 💰
artificial intelligence overview of it and more
Testing WebRTC applications at scale.pdf
WebRTC in SignalWire - troubleshooting media negotiation
Unit-3 cyber security network security of internet system
The Internet -By the Numbers, Sri Lanka Edition
APNIC Update, presented at PHNOG 2025 by Shane Hermoso
Job_Card_System_Styled_lorem_ipsum_.pptx

Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"