cheerio 效率比较

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));

结果对比

image.png

结论

执行速度上: substring > regex > cheerio

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容