Node.js、PHP与Python字符遍历性能实测对比

作者:夜航船时间:2026-10-28 12:48:43浏览:353

本文通过函数与类两种实现方式,对Node.js、PHP和Python三种语言在处理大字符串时的逐字符读取性能进行对比测试。测试结果显示,Node.js在两种模式下均保持最高效率,PHP次之,Python处理耗时相对较长。

测试方案与代码实现

本次测试旨在对比不同编程语言在处理大字符串时的性能表现,具体场景为对字符串进行逐字符读取。测试方案涵盖了函数式调用与面向对象类实现两种编程范式。

以下是具体的测试代码实现与结果分析。

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

函数


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

类


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

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

作者最新文章