Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
WebAssembly: Приручи дракона
Search
Polina Gurtovaya
June 27, 2020
Programming
2
440
WebAssembly: Приручи дракона
Производительность, V8, дракончики
Polina Gurtovaya
June 27, 2020
Tweet
Share
More Decks by Polina Gurtovaya
See All by Polina Gurtovaya
Не учите алгоритмы
hellsquirrel
1
860
Давайте все заблокируем
hellsquirrel
0
270
Wasmысле?
hellsquirrel
0
170
Магия декларативныx схем.
hellsquirrel
0
310
ML for HolyJS
hellsquirrel
0
94
Идеальный способ заблюрить белочку
hellsquirrel
0
120
ML/DL на фронте
hellsquirrel
0
160
InsertableStreams
hellsquirrel
0
68
WebRTC-404
hellsquirrel
0
470
Other Decks in Programming
See All in Programming
知られざるDMMデータエンジニアの生態 〜かつてツチノコと呼ばれし者〜
takaha4k
3
1.1k
[JAWS-UG横浜 #79] re:Invent 2024 の DB アップデートは Multi-Region!
maroon1st
0
130
個人アプリを2年ぶりにアプデしたから褒めて / I just updated my personal app, praise me!
lovee
0
300
Fibonacci Function Gallery - Part 2
philipschwarz
PRO
0
230
ペアーズでの、Langfuseを中心とした評価ドリブンなリリースサイクルのご紹介
fukubaka0825
1
200
Vue.jsでiOSアプリを作る方法
hal_spidernight
0
120
JavaScriptツール群「UnJS」を5分で一気に駆け巡る!
k1tikurisu
8
1.3k
Swiftコンパイラ超入門+async関数の仕組み
shiz
0
190
Spring gRPC について / About Spring gRPC
mackey0225
0
170
Amazon ECS とマイクロサービスから考えるシステム構成
hiyanger
1
180
ErdMap: Thinking about a map for Rails applications
makicamel
1
1.1k
Scaling your build logic
antalmonori
1
150
Featured
See All Featured
A Modern Web Designer's Workflow
chriscoyier
693
190k
Making the Leap to Tech Lead
cromwellryan
133
9.1k
Java REST API Framework Comparison - PWX 2021
mraible
28
8.4k
I Don’t Have Time: Getting Over the Fear to Launch Your Podcast
jcasabona
30
2.1k
Distributed Sagas: A Protocol for Coordinating Microservices
caitiem20
330
21k
How To Stay Up To Date on Web Technology
chriscoyier
790
250k
Thoughts on Productivity
jonyablonski
68
4.4k
Gamification - CAS2011
davidbonilla
80
5.1k
Put a Button on it: Removing Barriers to Going Fast.
kastner
60
3.7k
A designer walks into a library…
pauljervisheath
205
24k
Reflections from 52 weeks, 52 projects
jeffersonlam
348
20k
Designing for humans not robots
tammielis
250
25k
Transcript
WebAssembly: Приручи дракона
2
3
4
WebAssembly: Приручи дракона
6 Это доклад об очевидных вещах И немного о WebAssembly
7 Фронтенд — это песочница
8 Особенная песочница :)
9 Performance ∝ 1 ExecutionTime
10 Процессоры не понимают этот код function div() { return
Math.random() / 2; } const arr = []; for (let i = 0; i < 11088; i++) { arr[i] = div(); }
11 Зато понимают вот этот
12
13 Как сгенерировать код? function div(){…}
14 Compiler
15 Можно генерировать что угодно
16 Frontend Backend
17 Можно комбинировать frontend- и backend- части компиляторов
18 Цепочка IR может быть длинной
19 В промежуточное представление можно зашить оптимизации
20 #include <stdio.h> int main() { int result = 0;
for (int i = 0; i < 100; ++i) { if (i > 10) { result += i * 2; } else { result += i * 11; } } printf("%d\n", result); return 0; } define hidden i32 @main() local_unnamed_addr #0 { entry: %0 = tail call i32 (i8*, ...) @iprintf(…), i32 10395) ret i32 0 }
21 Магия компиляторов Function inlining Common subexpression elimination Constant propagations
Code motion Strength reduction Branch offset optimization Register allocation
22 IR, идеальное для Web Легко превратить в машинный код
Не зависит от архитектуры системы Компактное Легко парсить
23 WebAssembly is a binary instruction format for a stack-based
virtual machine. WebAssembly is a virtual ISA
24 (func (export "add") (param i32) (param i32) (result i32)
local.get 0 local.get 1 i32.add) add(1, 2) Module Memory Function Instruction Table
25 (module (func $i (import "imports" "logger") (param i32)) (memory
(import "imports" "importedMemory") 1) (func (export "exportedFunc") i32.const 42 call $i) (func (export "add") (param i32 i32) (result i32) local.get 0 local.get 1 i32.add) (data (i32.const 0) "Fifty"))
26 JavaScript pipeline
Готовим 27
28 Оптимизации занимают время, поэтому мы не можем оптимизировать весь
код
29 Hot functions function div() { return Math.random() / 2;
} const arr = []; for (let i = 0; i < 11088; i++) { arr[i] = div(); }
30 V8
31 Performance ∝ 1 ExecutionTime
32 WebAssembly pipeline
Готовим 33
34 Выполняем (V8)
35 Performance ∝ 1 ExecutionTime
36 +Кэширование Кэшируется прямо скомпилированный код! Если размер > 128
Кб
WebAssembly + JS 37 (module (func $i (import "imports" "logger")
(param i32)) (memory (import "imports" "importedMemory") 1) (func (export "exportedFunc") i32.const 42 call $i) (func (export "add") (param i32 i32) (result i32) local.get 0 local.get 1 i32.add) (data (i32.const 0) "dragon")) const importedMemory = new WebAssembly.Memory({ initial: 1, maximum: 10 }); WebAssembly.instantiateStreaming(fetch("simple.wasm"), { imports: { logger: function(arg) { console.log("first function call", arg); }, importedMemory } }).then(obj => { obj.instance.exports.exportedFunc(); const three = obj.instance.exports.add(1, 2); console.log("1 + 2 =", three); var memoryArray = new Uint32Array(importedMemory.buffer, 0, 10); console.log( "reading from memory", new TextDecoder("utf8").decode(memoryArray) ); });
38 Не то чтобы минусы… но все же Большие размеры
.wasm-файликов Отдельный этап подготовки Все медленно для языков с GC Нет SIMD (Single Instruction Multiple Data) Нет потоков MVP
39 WebAssembly в моем проекте Хочу портировать существующий код не
на JS Там т-а-а-а-кие бенчмарки! WebAssembly это модно! Большая часть нашей системы должна быть быстрой, мы уже оптимизировали все что могли
40 Спасибо! @polina_gurtovaya @pgurtovaya
[email protected]
40 @evilmartians @evilmartians_ru evilmartians.com github.com/HellSquirrel/wasm-talks