2017-09-06 102 views
1

我一直在使用shelljsshelljs性能很慢

在我的超级快速的系统我执行此过:

var shell = require('shelljs') 
const exec = require('child_process').exec 

console.time('shell mktemp -d') 
shell.exec('mktemp -d', {silent: true}) 
console.timeEnd('shell mktemp -d') 

console.time('child exec mktemp -d') 
exec('mktemp', ['-d'], function(error, stdout, stderr) { 
    if (error) { 
    console.error('stderr', stderr) 
    throw error 
    } 
    console.log('exec stdout', stdout) 
    console.timeEnd('child exec mktemp -d') 
}) 

它给下面的执行时间:

壳mktemp的-d: 208.126ms

exec stdout /tmp/tmp.w22tyS5Uyu

child exec mktemp -d:48.812ms

为什么shelljs会慢4倍?有什么想法吗?

+1

你看过shelljs代码,看看它是如何工作的,它是做什么的? – jfriend00

回答

1

,看一下shelljs是如何实现的: enter image description here

它完全依赖于node.js的FS库。这个库是跨平台的,用C++编写,但不像C语言那么高性能。更一般地说,你不能在JS中获得C中的perfs ...

另一件事,抽象层: 你使用的是exec(Command),其中Command是C定制的(Linux C在这里我认为)。机器创建一个线程并在其中执行一个命令。 当使用shell.js时,有许多机制可以确保交叉平台的形式,并将命令的抽象保留为函数并将结果保留为变量。请参阅shell.js中的exec代码: https://github.com/shelljs/shelljs/blob/master/src/exec.js 它并不真正与您的代码行完全相同。

希望有帮助!