Asynchronous , Non Blocking IO က ဘာကြောင့်ပို efficient ဖြစ်တာလဲ၊
ဒီနေရာမှာ မြန်တယ်လို့မသုံးပဲ efficent ဖြစ်တယ်လို့ပဲသုံးပါမယ်။
ဘာလို့ဆိုတော့ nonblocking IO proceesing မြန်တာ မဟုတ်ပဲ CPU ကို block မနေတဲ့အတွက် efficeint ဖြစ်တယ်လို့ဆိုချင်တာ။
ဥပမာ file ၂ ခုရဲ့ content ကို read ရမယ်ဆိုပါစို့။ read ပြီးမှ အဲ့ ၂ ဖိုင်ရဲ့ content ကို process လုပ်မယ်ဆိုပါစို့.
ဒါဆို synchronous နဲ့ဆိုဒီလိုရမယ်
read file1
read file2
process
အဲ့မှာ blocking ဖြစ်နေတဲ့အတွက် file1 read ပြီးမှ file 2 က ဆက်လုပ်လို့ရမယ် အဲ့အချိန်မှာစောင့်နေရတဲ့ CPU ဟာ သက်သက် waste ဖြစ်တယ် efficient မဖြစ်ဘူး။
Timeline အရဆို ဒီလိုဖြစ်မယ်။ ဆိုပါစို့ file1 က 20 milisecond ကြာမယ် ဖတ်တာ file2 ကလဲ အဲ့လောက်ပဲဆိုပါစို့။
ဒါဆို Timeline က အောက်က ပုံလိုဖြစ်မယ်.
——– file 1 read (20 milisecond)——- | ——-file2 read ( 20 milisecond)——
ဒါဆို total 40 milisecond လောက်ကြာမယ်။
ဒါဆို Asynchronous သုံးရင် ဒီလိုရမယ် Timeline က
——– file 1 read (20 milisecond)——-
——- file2 read ( 20 milisecond) ——-
file 2 read သည် file1 ပြီးအောင်စောင်စရာမလိုတဲ့အတွက် file 1 စဖတ်ပြီး IO device ကို control ပေးပြီး အချိန်မှာ သူက စသွားလို့ရတယ်၊
Concurrent run တဲ့ပုံစံဖြစ်သွားတယ် အဲ့တော့ သူက total အလွန်ဆုံးကြာမှ 25 လောက်ကပဲရှိမယ်။
အဲ့တော့ လက်တွေ့စမ်းချင်ရင် React JS တန်းက code ကိုယူစမ်းလို့ရတယ်။
အောက်က aysnc အတွက်ရေးထားတာ။
const fs = require(‘fs’);
let start = new Date();
console.log(“Start”);
let p1 = fs.promises.readFile(‘hello.txt’);
let p2 = fs.promises.readFile(‘hello2.txt’);
Promise.all([p1,p2]).then(data=>{
let end = new Date();
let time = end- start;
console.log(“Time “,time);
})
p1 p2 က promise ဖြစ်သွားမယ် aysnc နဲ့ Promise.all က အဲ့ ၂ခုကို တပြိုင်တည်းလွှတ်ပြီး result 2 ခုရတော့မှ then callback ကိုထ run ပေးမယ်။
Async code
https://github.com/mrthetkhine/TuringJSReact4thBatch/blob/master/chapter16/AsyncRead.js
အောက်က synchronous code နဲ့ run ကြည့်ပြီး ကိုယ်တိုင် စမ်းလို့ရတယ်။
const fs = require(‘fs’);
let start = new Date();
try {
console.log(“Start”);
const data = fs.readFileSync(‘hello.txt’, ‘utf8’);
//console.log(data);
const data2 = fs.readFileSync(‘hello2.txt’, ‘utf8’);
let end = new Date();
let time = end- start;
console.log(“Time “,time);
} catch (err) {
console.error(err);
}
https://github.com/mrthetkhine/TuringJSReact4thBatch/blob/master/chapter16/ReadSync.js
သတိထားဖို့က လက်ရှိ OS load နဲ့ နည်းနည်းဆိုင်မယ် ဒါပေမဲ့ ထပ်ခါ ထပ်ခါစမ်းရင်ပိုသိသာတယ်။
hello.txt, hello2.txt က content တူတူပဲ။ဖိုင်ကြီးလေ ပိုသိလာလေဖြစ်မယ်
Original link