SlideShare une entreprise Scribd logo
1  sur  32
My name is JavaScript
and I’m the fastest* language alive
* I wish 
Parallelism looks cool
…but implementations might hurt
Calculation in the main thread
// get inputs
var x = document.getElementById("x").value;
var y = document.getElementById("y").value;
// VERY useful calculations
for (var end = Date.now() + 3000; Date.now() < end; );
var result = x * y;
// output result
document.getElementById("output").value = result;
jsbin
Web Workers: client (main thread)
var worker = new Worker("worker.js");
worker.addEventListener("message", function (event) {
// output result
document.getElementById("output").value = event.data.result;
});
// get inputs
var x = document.getElementById("x").value;
var y = document.getElementById("y").value;
worker.postMessage({ x: x, y: y });
Web Workers: server (worker)
self.addEventListener("message", function (event) {
// get inputs
var x = event.data.x;
var y = event.data.y;
// VERY useful calculations
for (var end = Date.now() + 3000; Date.now() < end; );
var result = x * y;
postMessage({ result: result });
});
Web Workers: client (main thread)
var worker = new Worker("worker.js"), inc = 0;
// get inputs
var id = inc++;
var x = document.getElementById("x").value;
var y = document.getElementById("y").value;
worker.addEventListener("message", function handler(event) {
if (event.data.id === id) {
this.removeEventListener("message", handler);
// output result
document.getElementById("output").value = event.data.result;
}
});
worker.postMessage({ id: id, x: x, y: y });
Web Workers: server (worker)
self.addEventListener("message", function (event) {
// get inputs
var id = event.data.id;
var x = event.data.x;
var y = event.data.y;
// VERY useful calculations
for (var end = Date.now() + 3000; Date.now() < end; );
var result = x * y;
postMessage({ id: id, result: result });
});
jsbin
Calculation in the main thread
// get inputs
var x = document.getElementById("x").value;
var y = document.getElementById("y").value;
// VERY useful calculations
for (var end = Date.now() + 3000; Date.now() < end; );
var result = x * y;
// output result
document.getElementById("output").value = result;
Web Workers
//// index.js ////
var worker = new Worker("worker.js"), inc = 0;
// get inputs
var id = inc++;
var x = document.getElementById("x").value;
var y = document.getElementById("y").value;
worker.addEventListener("message", function
handler(event) {
if (event.data.id === id) {
this.removeEventListener("message", handler);
// output result
document.getElementById("output").value =
event.data.result;
}
});
worker.postMessage({ id: id, x: x, y: y });
//// worker.js ////
self.addEventListener("message", function (event) {
// get inputs
var id = event.data.id;
var x = event.data.x;
var y = event.data.y;
// VERY useful calculations
for (var end = Date.now() + 3000; Date.now() <
end;);
var result = x * y;
postMessage({ id: id, result: result });
});
Calculation in the main thread
// get inputs
var x = document.getElementById("x").value;
var y = document.getElementById("y").value;
// VERY useful calculations
for (var end = Date.now() + 3000; Date.now() < end; );
var result = x * y;
// output result
document.getElementById("output").value = result;
Dream API
parallel(function () {
// get inputs
var x = document.getElementById("x").value;
var y = document.getElementById("y").value;
// VERY useful calculations
for (var end = Date.now() + 3000; Date.now() < end;);
var result = x * y;
// output result
document.getElementById("output").value = result;
});
Let’s mix some stuff
ES6: Promise API
doSomethingAsync().then(
function onSuccess(result) {},
function onError(error) {}
)
// or just:
return doSomethingAsync().then(function (result) {
// do something with result
})
ES6: Promise API
$.ajax(url).then(function (data) {
$('#result').html(data);
var status = $('#status').html('Download complete.');
return status.fadeIn().promise().then(function () {
return sleep(2000);
}).then(function () {
return status.fadeOut();
});
});
ES6: Promise API
$.ajax(url).then(data => {
$('#result').html(data);
var status = $('#status').html('Download complete.');
return (
status.fadeIn().promise()
.then(() => sleep(2000))
.then(() => status.fadeOut())
);
});
ES7: async/await
var expr = await promise;
nextStatement();
var expr;
promise.then(result => {
expr = result;
nextStatement();
});
ES7: async/await
var data = await $.ajax(url);
$('#result').html(data);
var status = $('#status').html('Download complete.');
await status.fadeIn.promise();
await sleep(2000);
await status.fadeOut();
ES6: Proxy API
var proxy = new Proxy({}, {
get(target, name) {
return name;
},
set(target, name, value) {
console.log(name, '=', value);
},
// ...
});
proxy.a; // 'a'
proxy[0]; // '0'
proxy.a = 1; // console: 'a = 1'
proxy.b = 2; // console: 'b = 2'
ES6: Proxy API
var proxy = new Proxy({}, {
get(target, name) {
if (name === 'then') {
return new Promise(resolve => {
resolve(name);
});
}
}
});
proxy.a.then(result => console.log(result)); // 'a'
proxy[0].then(result => console.log(result)); // '0'
Let’s mix!
var proxy = new Proxy({}, {
get(target, name) {
if (name === 'then') {
return new Promise(resolve => {
resolve(name);
});
}
}
});
console.log(await proxy.a); // 'a'
console.log(await proxy[0]); // '0'
Let’s mix!
var handlers = {
get(target, name) {
var chain = { type: 'get', target, name };
if (name === 'then') {
return askMainThread(chain);
}
return new Proxy(chain, handlers);
}
};
var proxy = new Proxy({}, handlers);
proxy.a; // {type: 'get', target: {}, name: 'a'}
proxy.a.b; // {type: 'get', target: {…, name: 'a'}, name: 'b'}
await proxy.a.b.c; // 'a.b.c'
ES6: Proxy API
await proxy.document.getElementById('x').value
// into:
askMainThread({
type: 'get',
target: {
type: 'call',
target: {
type: 'get',
target: { type: 'get', target: {}, name: 'document' },
name: 'getElementById'
},
args: ['x']
},
name: 'value'
}).then(...)
ES7-powered API
parallel(async function (proxy) {
// get inputs
var x = await proxy.document.getElementById("x").value;
var y = await proxy.document.getElementById("y").value;
// VERY useful calculations
for (var end = Date.now() + 3000; Date.now() < end;);
var result = x * y;
// output result
proxy.document.getElementById("output").value = result;
});
ES7-powered API (just like dream!)
parallel(async function ({ document }) {
// get inputs
var x = await document.getElementById("x").value;
var y = await document.getElementById("y").value;
// VERY useful calculations
for (var end = Date.now() + 3000; Date.now() < end;);
var result = x * y;
// output result
document.getElementById("output").value = result;
});
See the Future
ES7: data parallelism
var ar = [1, 2, 3];
var arInc = ar.mapPar(val => val + 1); // [2, 3, 4]
var sum = ar.reducePar((x, y) => x + y); // 6
Int32Array.fromPar([1, 2, 3], val => val * 2); // int32[2, 4, 6]
// … even more … //
ES7: SharedArrayBuffer
(http://j.mp/sharedarraybuffer)
UI thread SharedArrayBuffer Web Worker
Thank you!

Contenu connexe

Tendances

Comprendre la programmation fonctionnelle, Blend Web Mix le 02/11/2016
Comprendre la programmation fonctionnelle, Blend Web Mix le 02/11/2016Comprendre la programmation fonctionnelle, Blend Web Mix le 02/11/2016
Comprendre la programmation fonctionnelle, Blend Web Mix le 02/11/2016Loïc Knuchel
 
Practical JavaScript Programming - Session 2/8
Practical JavaScript Programming - Session 2/8Practical JavaScript Programming - Session 2/8
Practical JavaScript Programming - Session 2/8Wilson Su
 
Юнит тестирование в Zend Framework 2.0
Юнит тестирование в Zend Framework 2.0Юнит тестирование в Zend Framework 2.0
Юнит тестирование в Zend Framework 2.0zfconfua
 
Practical JavaScript Programming - Session 3/8
Practical JavaScript Programming - Session 3/8Practical JavaScript Programming - Session 3/8
Practical JavaScript Programming - Session 3/8Wilson Su
 
Documentacion edderson callpa_ortiz
Documentacion edderson callpa_ortizDocumentacion edderson callpa_ortiz
Documentacion edderson callpa_ortizEdderson J. Ortiz
 
OpenResty/Lua 70+ Advanced Programming Skills and Optimization tips
OpenResty/Lua 70+ Advanced Programming Skills and Optimization tipsOpenResty/Lua 70+ Advanced Programming Skills and Optimization tips
OpenResty/Lua 70+ Advanced Programming Skills and Optimization tipsHo Kim
 
Assalamualaykum warahmatullahi wabarakatuu
Assalamualaykum warahmatullahi wabarakatuuAssalamualaykum warahmatullahi wabarakatuu
Assalamualaykum warahmatullahi wabarakatuuiswan_di
 
Collection pipeline par Mathieu Godart
Collection pipeline par  Mathieu GodartCollection pipeline par  Mathieu Godart
Collection pipeline par Mathieu GodartCocoaHeads France
 
Feeds. использование и создание плагинов. Feeds API
Feeds. использование и создание плагинов. Feeds APIFeeds. использование и создание плагинов. Feeds API
Feeds. использование и создание плагинов. Feeds APIAlex S
 
modern javascript, unobtrusive javascript, jquery
modern javascript, unobtrusive javascript, jquerymodern javascript, unobtrusive javascript, jquery
modern javascript, unobtrusive javascript, jqueryAdam Zygadlewicz
 
Silex. Микрофреймворк для микроприложений
Silex. Микрофреймворк для микроприложенийSilex. Микрофреймворк для микроприложений
Silex. Микрофреймворк для микроприложенийSoftline
 
Php codigos interfaces fredy guzman cusihunca
Php codigos interfaces   fredy guzman cusihuncaPhp codigos interfaces   fredy guzman cusihunca
Php codigos interfaces fredy guzman cusihuncaTigger_Fred
 
Simular un next del recordset en php de forma rudimentaria
Simular un next del recordset en php de forma rudimentariaSimular un next del recordset en php de forma rudimentaria
Simular un next del recordset en php de forma rudimentariajbersosa
 

Tendances (20)

Testování prakticky
Testování praktickyTestování prakticky
Testování prakticky
 
JQuery
JQueryJQuery
JQuery
 
Comprendre la programmation fonctionnelle, Blend Web Mix le 02/11/2016
Comprendre la programmation fonctionnelle, Blend Web Mix le 02/11/2016Comprendre la programmation fonctionnelle, Blend Web Mix le 02/11/2016
Comprendre la programmation fonctionnelle, Blend Web Mix le 02/11/2016
 
Index2
Index2Index2
Index2
 
Practical JavaScript Programming - Session 2/8
Practical JavaScript Programming - Session 2/8Practical JavaScript Programming - Session 2/8
Practical JavaScript Programming - Session 2/8
 
Silex al límite
Silex al límiteSilex al límite
Silex al límite
 
Юнит тестирование в Zend Framework 2.0
Юнит тестирование в Zend Framework 2.0Юнит тестирование в Zend Framework 2.0
Юнит тестирование в Zend Framework 2.0
 
Practical JavaScript Programming - Session 3/8
Practical JavaScript Programming - Session 3/8Practical JavaScript Programming - Session 3/8
Practical JavaScript Programming - Session 3/8
 
Documentacion edderson callpa_ortiz
Documentacion edderson callpa_ortizDocumentacion edderson callpa_ortiz
Documentacion edderson callpa_ortiz
 
1- Sourcecode Array
1- Sourcecode Array1- Sourcecode Array
1- Sourcecode Array
 
OpenResty/Lua 70+ Advanced Programming Skills and Optimization tips
OpenResty/Lua 70+ Advanced Programming Skills and Optimization tipsOpenResty/Lua 70+ Advanced Programming Skills and Optimization tips
OpenResty/Lua 70+ Advanced Programming Skills and Optimization tips
 
Assalamualaykum warahmatullahi wabarakatuu
Assalamualaykum warahmatullahi wabarakatuuAssalamualaykum warahmatullahi wabarakatuu
Assalamualaykum warahmatullahi wabarakatuu
 
Collection pipeline par Mathieu Godart
Collection pipeline par  Mathieu GodartCollection pipeline par  Mathieu Godart
Collection pipeline par Mathieu Godart
 
Feeds. использование и создание плагинов. Feeds API
Feeds. использование и создание плагинов. Feeds APIFeeds. использование и создание плагинов. Feeds API
Feeds. использование и создание плагинов. Feeds API
 
modern javascript, unobtrusive javascript, jquery
modern javascript, unobtrusive javascript, jquerymodern javascript, unobtrusive javascript, jquery
modern javascript, unobtrusive javascript, jquery
 
Silex. Микрофреймворк для микроприложений
Silex. Микрофреймворк для микроприложенийSilex. Микрофреймворк для микроприложений
Silex. Микрофреймворк для микроприложений
 
Jquery ui, ajax
Jquery ui, ajaxJquery ui, ajax
Jquery ui, ajax
 
Php codigos interfaces fredy guzman cusihunca
Php codigos interfaces   fredy guzman cusihuncaPhp codigos interfaces   fredy guzman cusihunca
Php codigos interfaces fredy guzman cusihunca
 
Simular un next del recordset en php de forma rudimentaria
Simular un next del recordset en php de forma rudimentariaSimular un next del recordset en php de forma rudimentaria
Simular un next del recordset en php de forma rudimentaria
 
Iteratory
IteratoryIteratory
Iteratory
 

Plus de Ingvar Stepanyan

A very quick intro to astrophotography
A very quick intro to astrophotographyA very quick intro to astrophotography
A very quick intro to astrophotographyIngvar Stepanyan
 
Asyncifying WebAssembly for the modern Web
Asyncifying WebAssembly for the modern WebAsyncifying WebAssembly for the modern Web
Asyncifying WebAssembly for the modern WebIngvar Stepanyan
 
Building fast interpreters in Rust
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in RustIngvar Stepanyan
 
How I tried to compile JavaScript
How I tried to compile JavaScriptHow I tried to compile JavaScript
How I tried to compile JavaScriptIngvar Stepanyan
 
AST - the only true tool for building JavaScript
AST - the only true tool for building JavaScriptAST - the only true tool for building JavaScript
AST - the only true tool for building JavaScriptIngvar Stepanyan
 
Creating own language made easy
Creating own language made easyCreating own language made easy
Creating own language made easyIngvar Stepanyan
 

Plus de Ingvar Stepanyan (10)

A very quick intro to astrophotography
A very quick intro to astrophotographyA very quick intro to astrophotography
A very quick intro to astrophotography
 
Asyncifying WebAssembly for the modern Web
Asyncifying WebAssembly for the modern WebAsyncifying WebAssembly for the modern Web
Asyncifying WebAssembly for the modern Web
 
Building fast interpreters in Rust
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in Rust
 
Rust ⇋ JavaScript
Rust ⇋ JavaScriptRust ⇋ JavaScript
Rust ⇋ JavaScript
 
How I tried to compile JavaScript
How I tried to compile JavaScriptHow I tried to compile JavaScript
How I tried to compile JavaScript
 
Your code is not a string
Your code is not a stringYour code is not a string
Your code is not a string
 
React for WinRT apps
React for WinRT appsReact for WinRT apps
React for WinRT apps
 
AST - the only true tool for building JavaScript
AST - the only true tool for building JavaScriptAST - the only true tool for building JavaScript
AST - the only true tool for building JavaScript
 
Creating own language made easy
Creating own language made easyCreating own language made easy
Creating own language made easy
 
JS: Audio Data Processing
JS: Audio Data ProcessingJS: Audio Data Processing
JS: Audio Data Processing
 

es6.concurrency()

  • 1. My name is JavaScript and I’m the fastest* language alive * I wish 
  • 4. Calculation in the main thread // get inputs var x = document.getElementById("x").value; var y = document.getElementById("y").value; // VERY useful calculations for (var end = Date.now() + 3000; Date.now() < end; ); var result = x * y; // output result document.getElementById("output").value = result;
  • 6. Web Workers: client (main thread) var worker = new Worker("worker.js"); worker.addEventListener("message", function (event) { // output result document.getElementById("output").value = event.data.result; }); // get inputs var x = document.getElementById("x").value; var y = document.getElementById("y").value; worker.postMessage({ x: x, y: y });
  • 7. Web Workers: server (worker) self.addEventListener("message", function (event) { // get inputs var x = event.data.x; var y = event.data.y; // VERY useful calculations for (var end = Date.now() + 3000; Date.now() < end; ); var result = x * y; postMessage({ result: result }); });
  • 8. Web Workers: client (main thread) var worker = new Worker("worker.js"), inc = 0; // get inputs var id = inc++; var x = document.getElementById("x").value; var y = document.getElementById("y").value; worker.addEventListener("message", function handler(event) { if (event.data.id === id) { this.removeEventListener("message", handler); // output result document.getElementById("output").value = event.data.result; } }); worker.postMessage({ id: id, x: x, y: y });
  • 9. Web Workers: server (worker) self.addEventListener("message", function (event) { // get inputs var id = event.data.id; var x = event.data.x; var y = event.data.y; // VERY useful calculations for (var end = Date.now() + 3000; Date.now() < end; ); var result = x * y; postMessage({ id: id, result: result }); });
  • 10. jsbin
  • 11. Calculation in the main thread // get inputs var x = document.getElementById("x").value; var y = document.getElementById("y").value; // VERY useful calculations for (var end = Date.now() + 3000; Date.now() < end; ); var result = x * y; // output result document.getElementById("output").value = result;
  • 12. Web Workers //// index.js //// var worker = new Worker("worker.js"), inc = 0; // get inputs var id = inc++; var x = document.getElementById("x").value; var y = document.getElementById("y").value; worker.addEventListener("message", function handler(event) { if (event.data.id === id) { this.removeEventListener("message", handler); // output result document.getElementById("output").value = event.data.result; } }); worker.postMessage({ id: id, x: x, y: y }); //// worker.js //// self.addEventListener("message", function (event) { // get inputs var id = event.data.id; var x = event.data.x; var y = event.data.y; // VERY useful calculations for (var end = Date.now() + 3000; Date.now() < end;); var result = x * y; postMessage({ id: id, result: result }); });
  • 13.
  • 14. Calculation in the main thread // get inputs var x = document.getElementById("x").value; var y = document.getElementById("y").value; // VERY useful calculations for (var end = Date.now() + 3000; Date.now() < end; ); var result = x * y; // output result document.getElementById("output").value = result;
  • 15. Dream API parallel(function () { // get inputs var x = document.getElementById("x").value; var y = document.getElementById("y").value; // VERY useful calculations for (var end = Date.now() + 3000; Date.now() < end;); var result = x * y; // output result document.getElementById("output").value = result; });
  • 17. ES6: Promise API doSomethingAsync().then( function onSuccess(result) {}, function onError(error) {} ) // or just: return doSomethingAsync().then(function (result) { // do something with result })
  • 18. ES6: Promise API $.ajax(url).then(function (data) { $('#result').html(data); var status = $('#status').html('Download complete.'); return status.fadeIn().promise().then(function () { return sleep(2000); }).then(function () { return status.fadeOut(); }); });
  • 19. ES6: Promise API $.ajax(url).then(data => { $('#result').html(data); var status = $('#status').html('Download complete.'); return ( status.fadeIn().promise() .then(() => sleep(2000)) .then(() => status.fadeOut()) ); });
  • 20. ES7: async/await var expr = await promise; nextStatement(); var expr; promise.then(result => { expr = result; nextStatement(); });
  • 21. ES7: async/await var data = await $.ajax(url); $('#result').html(data); var status = $('#status').html('Download complete.'); await status.fadeIn.promise(); await sleep(2000); await status.fadeOut();
  • 22. ES6: Proxy API var proxy = new Proxy({}, { get(target, name) { return name; }, set(target, name, value) { console.log(name, '=', value); }, // ... }); proxy.a; // 'a' proxy[0]; // '0' proxy.a = 1; // console: 'a = 1' proxy.b = 2; // console: 'b = 2'
  • 23. ES6: Proxy API var proxy = new Proxy({}, { get(target, name) { if (name === 'then') { return new Promise(resolve => { resolve(name); }); } } }); proxy.a.then(result => console.log(result)); // 'a' proxy[0].then(result => console.log(result)); // '0'
  • 24. Let’s mix! var proxy = new Proxy({}, { get(target, name) { if (name === 'then') { return new Promise(resolve => { resolve(name); }); } } }); console.log(await proxy.a); // 'a' console.log(await proxy[0]); // '0'
  • 25. Let’s mix! var handlers = { get(target, name) { var chain = { type: 'get', target, name }; if (name === 'then') { return askMainThread(chain); } return new Proxy(chain, handlers); } }; var proxy = new Proxy({}, handlers); proxy.a; // {type: 'get', target: {}, name: 'a'} proxy.a.b; // {type: 'get', target: {…, name: 'a'}, name: 'b'} await proxy.a.b.c; // 'a.b.c'
  • 26. ES6: Proxy API await proxy.document.getElementById('x').value // into: askMainThread({ type: 'get', target: { type: 'call', target: { type: 'get', target: { type: 'get', target: {}, name: 'document' }, name: 'getElementById' }, args: ['x'] }, name: 'value' }).then(...)
  • 27. ES7-powered API parallel(async function (proxy) { // get inputs var x = await proxy.document.getElementById("x").value; var y = await proxy.document.getElementById("y").value; // VERY useful calculations for (var end = Date.now() + 3000; Date.now() < end;); var result = x * y; // output result proxy.document.getElementById("output").value = result; });
  • 28. ES7-powered API (just like dream!) parallel(async function ({ document }) { // get inputs var x = await document.getElementById("x").value; var y = await document.getElementById("y").value; // VERY useful calculations for (var end = Date.now() + 3000; Date.now() < end;); var result = x * y; // output result document.getElementById("output").value = result; });
  • 30. ES7: data parallelism var ar = [1, 2, 3]; var arInc = ar.mapPar(val => val + 1); // [2, 3, 4] var sum = ar.reducePar((x, y) => x + y); // 6 Int32Array.fromPar([1, 2, 3], val => val * 2); // int32[2, 4, 6] // … even more … //