Experiments in optimising three.js

For today’s Cardboctober hack, I decided to do some investigation instead.

Square roots

The first thing I wanted to test is the .length() method. The computation for the length of a vector uses Pythagoras’s theorem; which you may remember requires a square root.

var radius = 50;
if (someVector.length() < radius) { ... }
var radiusSquared = Math.pow(50, 2);
if (someVector.lengthSq() < radiusSquared) { ... }

Object instantiation

The next thing I wanted to look at is object instantiation vs. reuse. Many modern Javascript APIs have adopted a functional style, where each method creates a new instance of an object.

var a = Vector.create([1, 2, 3]);
var b = Vector.create([4, 5, 6]);
var c = a.add(b);

Lessons learned

I expected this to be a simple exercise validating my assumptions, what I got was a reminder that developers are weirdly superstitious and untested optimisation is micro-optimsation.