npm i cheerio
time-$.js
const cheerio = require('cheerio');
const $ = cheerio.load('<h2 class="title">Hello world</h2>');
$('h2.title').text('Hello there!');
$('h2').addClass('welcome');
var html = $.html(); //=> <html><head></head><body><h2 class="title welcome">Hello there!</h2></body></html>
const t = process.hrtime();
for (let i = 0; i < 1000000; i++) {
$('h2.title').text()
}
console.log(process.hrtime(t));
time-regex.js
const cheerio = require('cheerio');
const $ = cheerio.load('<h2 class="title">Hello world</h2>');
$('h2.title').text('Hello there!');
$('h2').addClass('welcome');
var html = $.html(); //=> <html><head></head><body><h2 class="title welcome">Hello there!</h2></body></html>
const t = process.hrtime();
for (let i = 0; i < 1000000; i++) {
html.match(/>[^>]+!/);
}
console.log(process.hrtime(t));
time-substring.js
const cheerio = require('cheerio');
const $ = cheerio.load('<h2 class="title">Hello world</h2>');
$('h2.title').text('Hello there!');
$('h2').addClass('welcome');
var html = $.html(); //=> <html><head></head><body><h2 class="title welcome">Hello there!</h2></body></html>
const t = process.hrtime();
for (let i = 0; i < 1000000; i++) {
let i_start = html.indexOf('Hello');
let i_end = html.indexOf('there!');
html.substring(i_start, i_end + 6)
}
console.log(process.hrtime(t));
结果对比
结论
执行速度上: substring > regex > cheerio