Node.js和PHP運行機制對比

來源:互聯網
上載者:User

標籤:charset   優點   回呼函數   高並發   nod   file   案頭   恢複   row   

為什麼要用node.js它又有什麼優勢呢?一個新的技術被大家喜愛那麼它就必然有它的優勢,那麼下面我們就來簡單把它和php做一個對比

1 . Node.js 他用的是JavaScript引擎,那麼註定它是單線程 ,使用非同步方法呼叫開闢多個任務,無需像php等待上個任務線程使用結束之後給下個使用,

   PHP也是單線程但是它借用Apache伺服器提供多線程服務

2 . 高並發,大資料量怎麼處理:php : 最佳化sql ,用組件,用緩衝,為了讓線程儘快結束,進行下一次任務node:單線程 、非同步、事件驅動 下面是他們處理事件,     php上下銜接依次執行,     node中因為運行速度很快並不會等待,所以如果後面用到前面返回的結果,就需要把後面的封裝起來,作為一個回呼函數執行node.js vs php 優點:  效能高(運行機制問題)  開發效率高(省不少最佳化的事)  應用範圍廣(可以開發案頭系統,electron架構)缺點:  新、人少  中介軟體少  IDE不完善  node.js的劣勢和解決方案    1 預設不支援多核,但可以用cluster解決  2 預設不支援伺服器叢集,node-http-proxy可以解決  3 使用nginx做負載平衡,靜態由nginx處理,動態有node.js處理  4 forever或node-cluster實現災難恢複  下面是 一個資料測試  請求-->隨機建立內容是20k字元的文檔 -->讀取文檔 -->輸出  結果是 node所需的時間要遠小於php所用的時間1 Node  
var  http  =  require ( ‘http‘ ) ;     http.createServer ( function  handler ( req ,  res )   {    res.writeHead ( 200 , {‘Content-Type‘ : ‘text/html ; charset=utf-8‘ });    if (req.url !== ‘/favicon.ico‘) {        str = "" ;   //隨機字元 - 20k        //隨機組建檔案        fileName = String.fromCharCode ( Math. floor ( 65 + ( Math. random () * ( 122 - 65 )))) + ".txt" ;        //str 賦值         for ( i = 0; i < 200000; i++ ){            n = Math. floor ( 65 + ( Math. random () * ( 122 - 65 )) ) ;            str += String. fromCharCode ( n ) ;         }        //寫入        var fs = require ( ‘fs‘ ) ;//操作檔案模組        //寫入內容        fs.writeFile ( fileName,str,function ( err, fd )   {                 if ( err ) throw  err ; //如果錯誤則拋出錯誤                 //讀取檔案 並展示的頁面                fs.readFile ( fileName , function( err, data ){                    if   ( err )   throw  err ;                     res.write(data);//輸出                    res.end (‘‘) ; // 結束                 }) ;                }         );    }}).listen(8000) ;console. log ( ‘success:8000‘ ) ;

 

PHP

  

 1 <?php 2  3 $str = "" ;   //隨機字串 4 // 文本名字 5 $fileName   = chr ( rand ( 0 , 57 ) + 65 ).‘.txt‘ ; 6  7 for ( $i = 0 ; $i < 200000 ; $i ++ ){ 8  9      $n = rand ( 0 , 57 ) + 65 ;10      $str   =   $str . chr ( $n ) ;11 }12 13 //寫入14 15 file_put_contents( $fileName , $str ) ;16 17 $result = file_get_contents ( $fileName ) ;18 19 echo $result ;20 ?>

Node.js和PHP運行機制對比

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.