首页 > web前端 > js教程 > 正文

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

WBOY
发布: 2016-05-16 16:42:28
原创
2399 人浏览过

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

测试代码

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学习者快速成长!