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
470
WebAssembly: Приручи дракона
Производительность, V8, дракончики
Polina Gurtovaya
June 27, 2020
Tweet
Share
More Decks by Polina Gurtovaya
See All by Polina Gurtovaya
Не учите алгоритмы
hellsquirrel
1
890
Давайте все заблокируем
hellsquirrel
0
280
Wasmысле?
hellsquirrel
0
190
Магия декларативныx схем.
hellsquirrel
0
320
ML for HolyJS
hellsquirrel
0
120
Идеальный способ заблюрить белочку
hellsquirrel
0
140
ML/DL на фронте
hellsquirrel
0
170
InsertableStreams
hellsquirrel
0
77
WebRTC-404
hellsquirrel
0
490
Other Decks in Programming
See All in Programming
GitHub Copilot for Azureを使い倒したい
ymd65536
1
310
Enterprise Web App. Development (1): Build Tool Training Ver. 5
knakagawa
1
120
2ヶ月で生産性2倍、お買い物アプリ「カウシェ」4チーム同時改善の取り組み
ike002jp
1
110
The Implementations of Advanced LR Parser Algorithm
junk0612
1
1.3k
開発者フレンドリーで顧客も満足?Platformの秘密
algoartis
0
160
Optimizing JRuby 10
headius
0
570
「理解」を重視したAI活用開発
fast_doctor
0
270
Носок на сок
bo0om
0
1.1k
REALITY コマンド作成チュートリアル
nishiuriraku
0
120
State of Namespace
tagomoris
5
2.4k
スモールスタートで始めるためのLambda×モノリス(Lambdalith)
akihisaikeda
2
340
The Nature of Complexity in John Ousterhout’s Philosophy of Software Design
philipschwarz
PRO
0
160
Featured
See All Featured
VelocityConf: Rendering Performance Case Studies
addyosmani
329
24k
Building a Modern Day E-commerce SEO Strategy
aleyda
40
7.2k
For a Future-Friendly Web
brad_frost
177
9.7k
CSS Pre-Processors: Stylus, Less & Sass
bermonpainter
357
30k
Become a Pro
speakerdeck
PRO
28
5.3k
How to train your dragon (web standard)
notwaldorf
91
6k
Code Review Best Practice
trishagee
67
18k
Refactoring Trust on Your Teams (GOTO; Chicago 2020)
rmw
34
2.9k
[RailsConf 2023 Opening Keynote] The Magic of Rails
eileencodes
29
9.4k
Designing Experiences People Love
moore
142
24k
Docker and Python
trallard
44
3.4k
Building Adaptive Systems
keathley
41
2.5k
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