首頁 > web前端 > js教程 > 主體

Node.js與PHP、Python的字元處理效能比較_node.js

WBOY
發布: 2016-05-16 16:42:28
原創
2375 人瀏覽過

測試案例分為用函數和類別來進行一個大字串的字元逐一讀取。

測試程式碼

Node.js

函數

var fs = require("fs");

var content = fs.readFileSync("page.html", {
 encoding: "utf-8"
});

function chars(content){
 var length = content.length;
 var pos = 0;
 while(pos ++ < length){
  var chr = content[pos - 1];
 }
}
var start = Date.now();
chars(content);
var end = Date.now();
console.log(end - start);
登入後複製

類別

var fs = require("fs");

var content = fs.readFileSync("page.html", {
 encoding: "utf-8"
});

var Chars = function(str){
 this.str = str;
 this.length = str.length
 this.pos = 0;
}
Chars.prototype.run = function(){
 while(this.pos ++ < this.length){
  var chr = this.str[this.pos - 1];
 }
}
var start = Date.now();
var instance = new Chars(content);
instance.run();
var end = Date.now();
console.log(end - start);
登入後複製

PHP

函數

<&#63;php
function chars($content){
 $length = strlen($content);
 $pos = 0;
 while ($pos ++ < $length) {
  $char = $content{$pos - 1};
 }
}
$content = file_get_contents("page.html");
$start = microtime(true);
chars($content);
$end = microtime(true);
echo ($end - $start) . "\n";
&#63;>
登入後複製

類別

<&#63;php
class Chars{
 public function __construct($str){
  $this->str = $str;
  $this->length = strlen($str);
  $this->pos = 0;
 }
 public function run(){
  while($this->pos++ < $this->length){
   $char = $this->str{$this->pos - 1};
  }
 }
}
$content = file_get_contents("page.html");
$start = microtime(true);
$instance = new Chars($content);
$instance->run();
$end = microtime(true);
echo ($end - $start) . "\n";
&#63;>
登入後複製

Python

函數

import codecs
import time

def chars(content):
 length = len(content)
 pos = 0
 while(pos < length):
  char = content[pos]
  pos = pos + 1

f = codecs.open('page.html', encoding='utf-8')

content = f.read()

start = time.time()
chars(content)
end = time.time();

print end - start
登入後複製

類別

import codecs
import time

class Chars(): 
 def __init__(self, str): 
  self.str = str
  self.length = len(str)
  self.pos = 0

 def run(self):
  while(self.pos < self.length):
   char = self.str[self.pos]
   self.pos = self.pos + 1

f = codecs.open('page.html', encoding='utf-8')

content = f.read()

start = time.time()
instance = Chars(content)
instance.run()
end = time.time();

print (end - start)
登入後複製

其中 page.html 檔案內容為一個長度為 的文字。

測試結果

语言 函数 类
Node.js 0.022s 0.026s
PHP 0.35s 1.02s
Python 0.58s 1.50s
登入後複製

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!