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
Sponsored
·
Your Podcast. Everywhere. Effortlessly.
Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
→
Polina Gurtovaya
June 27, 2020
Programming
2
500
WebAssembly: Приручи дракона
Производительность, V8, дракончики
Polina Gurtovaya
June 27, 2020
Tweet
Share
More Decks by Polina Gurtovaya
See All by Polina Gurtovaya
Не учите алгоритмы
hellsquirrel
1
1k
Давайте все заблокируем
hellsquirrel
0
340
Wasmысле?
hellsquirrel
0
260
Магия декларативныx схем.
hellsquirrel
0
370
ML for HolyJS
hellsquirrel
0
170
Идеальный способ заблюрить белочку
hellsquirrel
0
180
ML/DL на фронте
hellsquirrel
0
220
InsertableStreams
hellsquirrel
0
110
WebRTC-404
hellsquirrel
0
550
Other Decks in Programming
See All in Programming
CSC307 Lecture 05
javiergs
PRO
0
480
Honoを使ったリモートMCPサーバでAIツールとの連携を加速させる!
tosuri13
1
150
ThorVG Viewer In VS Code
nors
0
750
フロントエンド開発の勘所 -複数事業を経験して見えた判断軸の違い-
heimusu
7
2.6k
Spinner 軸ズレ現象を調べたらレンダリング深淵に飲まれた #レバテックMeetup
bengo4com
1
220
LLM Observabilityによる 対話型音声AIアプリケーションの安定運用
gekko0114
2
390
メルカリのリーダビリティチームが取り組む、AI時代のスケーラブルな品質文化
cloverrose
2
490
Implementation Patterns
denyspoltorak
0
240
Python札幌 LT資料
t3tra
7
1.1k
MDN Web Docs に日本語翻訳でコントリビュート
ohmori_yusuke
0
590
Fragmented Architectures
denyspoltorak
0
120
組織で育むオブザーバビリティ
ryota_hnk
0
130
Featured
See All Featured
Statistics for Hackers
jakevdp
799
230k
Introduction to Domain-Driven Design and Collaborative software design
baasie
1
560
The Mindset for Success: Future Career Progression
greggifford
PRO
0
220
Put a Button on it: Removing Barriers to Going Fast.
kastner
60
4.1k
StorybookのUI Testing Handbookを読んだ
zakiyama
31
6.5k
Save Time (by Creating Custom Rails Generators)
garrettdimon
PRO
32
1.9k
Bootstrapping a Software Product
garrettdimon
PRO
307
120k
The Invisible Side of Design
smashingmag
302
51k
Design in an AI World
tapps
0
130
Learning to Love Humans: Emotional Interface Design
aarron
275
41k
Everyday Curiosity
cassininazir
0
120
I Don’t Have Time: Getting Over the Fear to Launch Your Podcast
jcasabona
34
2.6k
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