前端开发

 首页 > 前端开发 > nodejs > Node.js与PHP、Python的字符处理性能对比_node.js

Node.js与PHP、Python的字符处理性能对比_node.js

分享到:
【字体:
导读:
          因为后续考虑实现 Fl 引擎的Node.js版本,所以对比了下Node.js和PHP的字符处理性能。发现Node.js真是甩了PHP几条街啊,再测试了下Python,比PHP还慢。...

测试用例分为用函数和类来进行一个大字符串的字符逐一读取。

测试代码

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

函数


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";
?>

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

分享到:
在Linux上用forever实现Node.js项目自启...
那么能否利用forever加启动脚本方式解决上述问题呢?答案当然是肯定的,只不过有点麻烦,而且forever官方缺少详细的配置文档。我在配置的时候也走了一些弯路,下面详细来说。 注:本文的实验环境是Ubuntu Server 12.04 LTS x86_64,在CentOS上的配置更简单一些 最早,我想着试试在/etc/rc.local中增加一句forever start x...
基于promise.js实现nodejs的promises库_n...
今天从GIT源码库中下载了promise.js,发现该源码是基于Web前端JavaScript写的,并不能直接用于nodejs。还好代码不是很多,也不是很复杂。经过分析整合,将其实现为nodejs的一个框架,代码如下: (function(){ /** * Copyright 2012-2013 (c) Pierre Duquesne * script: promise.js * description: promises的node...
  •         php迷,一个php技术的分享社区,专属您自己的技术摘抄本、收藏夹。
  • 在这里……