【发布时间】:2019-05-22 03:41:02
【问题描述】:
最近我一直在尝试使用 Web workers 接口来试验 JavaScript 中的线程。
尝试使用网络工作者制作包含,请执行以下步骤:
- 将初始数组拆分为大小相等的部分
- 为每个在该片段上运行 .contains 的片段创建一个网络工作者
- 如果在任何片段中找到该值,则返回 true,而无需等待所有工作人员完成。
这是我尝试过的:
var MAX_VALUE = 100000000;
var integerArray = Array.from({length: 40000000}, () => Math.floor(Math.random() * MAX_VALUE));
var t0 = performance.now();
console.log(integerArray.includes(1));
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
var promises = [];
var chunks = [];
while(integerArray.length) {
chunks.push(integerArray.splice(0,10000000));
}
t0 = performance.now();
chunks.forEach(function(element) {
promises.push(createWorker(element));
});
function createWorker(arrayChunk) {
return new Promise(function(resolve) {
var v = new Worker(getScriptPath(function(){
self.addEventListener('message', function(e) {
var value = e.data.includes(1);
self.postMessage(value);
}, false);
}));
v.postMessage(arrayChunk);
v.onmessage = function(event){
resolve(event.data);
};
});
}
firstTrue(promises).then(function(data) {
// `data` has the results, compute the final solution
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
});
function firstTrue(promises) {
const newPromises = promises.map(p => new Promise(
(resolve, reject) => p.then(v => v && resolve(true), reject)
));
newPromises.push(Promise.all(promises).then(() => false));
return Promise.race(newPromises);
}
//As a worker normally take another JavaScript file to execute we convert the function in an URL: http://stackoverflow.com/a/16799132/2576706
function getScriptPath(foo){ return window.URL.createObjectURL(new Blob([foo.toString().match(/^\s*function\s*\(\s*\)\s*\{(([\s\S](?!\}$))*[\s\S])/)[1]],{type:'text/javascript'})); }
任何浏览器和cpu都试过了,与只对初始数组做一个简单的包含相比,速度非常慢。
为什么这么慢? 上面的代码有什么问题?
参考文献
编辑:问题不在于具体的 .contains() ,而可能是其他数组函数,例如.indexOf()、.map()、forEach() 等。为什么在 web worker 之间拆分工作需要更长的时间...
【问题讨论】:
-
我打算做更多的研究并发表更好的评论,但我想知道这是否可能是由于本机
includes方法的性能缓慢造成的。
标签: javascript web-worker