Skip to content

Instantly share code, notes, and snippets.

View psiphi75's full-sized avatar

Simon Werner psiphi75

View GitHub Profile
@psiphi75
psiphi75 / worker.js
Last active February 28, 2017 09:25
Example of WebWorker worker
// This is our computation, we just initialise it for now.
var rt = new RayTracer(700, 700);
// we are in the worker.js thread so 'this' has the correct scope.
this.addEventListener('message', function(e) {
// Start the work
if (e.message === 'Start your work') {
var result = rt.raytrace();
// ... continuing from code above.
// We create the worker, the work can actally begin (but will give the
// worker a message to start later).
var worker = new UniversalWorker(uri);
// Listen to all messages from the worker.
worker.addEventListener('message', waitForResult, { once: true });
// We send a message to the worker, this can be any primitive or object,
@psiphi75
psiphi75 / detect-nodejs.js
Last active February 28, 2017 08:52
Implementing workerjs in code that is used both in the browser and in Node.js
// A reliable method to detect if we are running in Node.js
const isNodeJS = new Function('try {return this===global;}catch(e){return false;}')();
var UniversalWorker;
var uri;
if (isNodeJS) {
// Dynamically load "workerjs"
UniversalWorker = require('workerjs');
@psiphi75
psiphi75 / polymorphic.js
Created February 14, 2017 21:33
Example of polymorphic and monomorphic code
function add(a, b) {
return a + b;
}
add(1, 2); // Starts as monomorphic
add(2, 3); // Still monomorphic
add('x', 'y'); // Now becomes polymorphic - bad for optimisation
fuction vector(x, y) {
this.x = x;
this.y = y;
}
const a = new vector(1, 2);
const b = new vector(3, 4); // OKAY: b has the same hidden class as a
b.z = 5; // BAD: b now has a different hidden class
@psiphi75
psiphi75 / vector.dot.js
Created February 13, 2017 03:55
Vector using the classic prototypical object.
function Vector(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
}
Vector.prototype.dot = function(w) {
return this.x * w.x + this.y * w.y + this.z * w.z;
};
// ... more vector functions
@psiphi75
psiphi75 / vector.dot.js
Last active February 13, 2017 03:14
The vector.dot function - it's simple right!?
var vector = {
make: function (x, y, z) {
if (x instanceof Array) {
return [x[0], x[1], x[2]];
} else {
return [x, y, z];
}
},
dot: function (v, w) {
return (v[0] * w[0] + v[1] * w[1] + v[2] * w[2]);
@psiphi75
psiphi75 / run-server.js
Created February 13, 2017 01:31
Create a CPU profile using Node.js and v8-profiler
var profiler = require('v8-profiler');
var fs = require('fs');
var processStartTime = new Date().getTime();
profiler.startProfiling();
while (true) {
rt.renderFrame(done);