Node.js与PHP、Python的字符处理性能对比
测试用例分为用函数和类来进行一个大字符串的字符逐一读取。
测试代码
Node.js
函数
varfs=require("fs");
varcontent=fs.readFileSync("page.html",{
encoding:"utf-8"
});
functionchars(content){
varlength=content.length;
varpos=0;
while(pos++<length){
varchr=content[pos-1];
}
}
varstart=Date.now();
chars(content);
varend=Date.now();
console.log(end-start);
类
varfs=require("fs");
varcontent=fs.readFileSync("page.html",{
encoding:"utf-8"
});
varChars=function(str){
this.str=str;
this.length=str.length
this.pos=0;
}
Chars.prototype.run=function(){
while(this.pos++<this.length){
varchr=this.str[this.pos-1];
}
}
varstart=Date.now();
varinstance=newChars(content);
instance.run();
varend=Date.now();
console.log(end-start);
PHP
函数
<?php
functionchars($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";
?>
类
<?php
classChars{
publicfunction__construct($str){
$this->str=$str;
$this->length=strlen($str);
$this->pos=0;
}
publicfunctionrun(){
while($this->pos++<$this->length){
$char=$this->str{$this->pos-1};
}
}
}
$content=file_get_contents("page.html");
$start=microtime(true);
$instance=newChars($content);
$instance->run();
$end=microtime(true);
echo($end-$start)."\n";
?>
Python
函数
importcodecs
importtime
defchars(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();
printend-start
类
importcodecs
importtime
classChars():
def__init__(self,str):
self.str=str
self.length=len(str)
self.pos=0
defrun(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.js0.022s0.026s PHP0.35s1.02s Python0.58s1.50s