Three.js: Frustum.intersectsObject's weird performance behavior

Created on 12 Aug 2019  路  1Comment  路  Source: mrdoob/three.js

I find that Frustum.intersectsObject is always slower in the first loop call, and get faster in the loop calls followed. I call 10000 times in a loop and call the loop for 10 times and the Performance.now() gap logs:

  1. 10.914999998931307 first time!
  2. 2.134999998816056
  3. 1.8749999999272404
  4. 2.5299999997514533
  5. 2.4800000010145595
  6. 2.440000000206055
  7. 2.3700000001554145
  8. 2.269999999043648
  9. 8.120000000417349
  10. 1.9350000002305023

It's really weird since it always runs the exact same codes each loop. But the time log is always like that. I really don't know why馃槩

My test code:

// create test meshes
const SEGMENTS = 16;
const DC = 10000;
var geometry = new THREE.SphereBufferGeometry(0.05, SEGMENTS, SEGMENTS);
for (let i = 0; i < DC; i++) {
    var material = new THREE.MeshBasicMaterial({
        color: new THREE.Color(Math.random(), Math.random(), Math.random())
    });
    mesh = new THREE.Mesh( geometry, material );
    mesh.position.set(Math.random() * 5.0 - 2.5, Math.random() * 5.0 - 2.5, Math.random() * 5.0 - 2.5);
    meshes.push(mesh);

    geometry.computeBoundingSphere();

    mesh.frustumCulled = true;

    scene.add( mesh );
}

// test Frustum.intersectsObject
const frustum = new THREE.Frustum();
frustum.setFromMatrix(camera.projectionMatrix, camera.matrixWorldInverse);
let sum = 0;
for (let i = 0; i < 10; i++) {
    const tic = performance.now();
    for (let i = 0; i < meshes.length; i++) {
        frustum.intersectsObject(meshes[i]);
    }
    const nowC = performance.now() - tic;
    console.log(nowC)
    sum += nowC;
}
Three.js version
  • [x ] Dev
  • [ ] r107
  • [ ] ...
Browser
  • [] All of them
  • [x ] Chrome
  • [ ] Firefox
  • [ ] Internet Explorer
OS
  • [] All of them
  • [ ] Windows
  • [x ] macOS
  • [ ] Linux
  • [ ] Android
  • [ ] iOS
Hardware Requirements (graphics card, VR Device, ...)
Question

Most helpful comment

Live demo: https://jsfiddle.net/qar2of8z/1/

JavaScript engines optimize code execution so it's non unusual that this happens. Hence, it's recommended to average performance metrics over a certain amount of time and always compare these values.

>All comments

Live demo: https://jsfiddle.net/qar2of8z/1/

JavaScript engines optimize code execution so it's non unusual that this happens. Hence, it's recommended to average performance metrics over a certain amount of time and always compare these values.

Was this page helpful?
0 / 5 - 0 ratings