JavaScript的記憶函數真的可以提升效能嗎?

來源:互聯網
上載者:User

標籤:data   class   push   聲明   hash   功能   日常   儲存   undefined   

  1 記憶函數是什麼呢?讓函數記住曾經計算過的參數對應的結果 2 那我們為什麼使用記憶函數呢?答案是 避免重複計算 3 在工作中如何使用和實現函數記憶 ?形成閉包,在閉包中維護一個雜湊數組(其實就是對象),讓雜湊數組幫你記住曾經你做過的計算 請看下面的例子:(計算質數) 先寫兩個函數  第一個數帶記憶功能的:   let isPrime = (function () {      let hash = {//雜湊中儲存類似這樣的結構         //8: false,         //7: true       }       let isPrime = (n)=> { // 返回內層函數          if (n <3) {              return true           } else if (hash[n] !==undefined) {               return hash[n]           } else {              for (leti = 2; i < Math.sqrt(n);i++) {                  if (n%i ==0) {                     return hash[n] =false;                  }              }             return hash[n] =true          }      }     return isPrime })() //這個函數使用閉包 和 一個對象(實現記憶)

 

第二個是個普通函數   let isPrime1 = (n)=> {     if (n <3) {        return true      } else {         for (leti = 2; i < Math.sqrt(n);i++) {            if (n%i ==0) {                return false;            }        }       return true     } } 然後我們來見證一下他們的區別吧~~~~   // 先聲明一個空數組 我往裡push 1000000 個 1100 以內的 隨機數   let array = [] for (leti = 0; i < 1000000; i++) {      array.push(parseInt(Math.random() *1100 )) } 進入測試階段 ~~~ (利用console.time 和 console.Endtime)看看執行時間.....  // 這個是沒有帶函數記憶的~~
console.time(‘isPrime1‘) for (leti = 0; i < array.length;i++) {    isPrime1(array[i])  } console.timeEnd(‘isPrime1‘)    // 這個是帶函數記憶的
console.time(‘isPrime‘)
for (leti = 0; i < array.length;i++) {     isPrime(array[i]) } console.timeEnd(‘isPrime‘) 下面就是結果了~~
日常項目中能用到的話,也可以提升些效能吧~~~^_^

jpg 改 rar

JavaScript的記憶函數真的可以提升效能嗎?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.