core-estimator
core-estimator copied to clipboard
Particular gotcha for accidentally and silently burning CPU cycles
For a long time, I have been using core estimator as a polyfill and everything has been working smoothly. Recently, on a site I've been developing, I started getting really odd situations where the browser would continuously consume 100% of a single CPU core.
It turns out that I had misconfigured the installation of core estimator, and I had had the following code in my main .html file:
<html>
...
<head>
<script src='core-estimator/core-estimator.min.js'></script>
<script src='core-estimator/workload.js'></script>
...
</head>
...
</html>
This does not create any errors or warnings, and everything works, but the configuration mistake was that script workload.js was never intended to be included in the main html file. When it is included, it installs a self.onmessage handler to the top window, which postMessage(null)s to itself, causing workload.js to infinitely loop messages to itself the moment that anything else is postMessaged to the web page. This kind of error can easily go unseen, since it just silently burns CPU cycles on the background.
Perhaps workload.js could have checks in it before installing onmessage that the script context is actually inside a web worker, and if not, it would throw an exception "workload.js is not supposed to be included in main thread" or something similar? This would explicitly prevent such misconfigurations to silently turn into cycle wasting CPU busy spin loops.
Check performance in the context of Web Worker:
var isInWorker = ( typeof WorkerGlobalScope != 'undefined' ) && ( self instanceof WorkerGlobalScope );
if ( isInWorker ) {
// use self and etc... // under Worker
} else {
// use window and etc... // sim method onmessage // under page
}
Just write your workload.js
Sure, I'll probably accept any well-formatted pullreq adding that.
Ok, I will make soon