Performance Issue in three.js while creating large number of objects and its solution


Few days back I am creating a demo using three.js library(used for rendering 3D objects). I have added three to four geometry on the scene. It was working just fine as well with animation added to it. But when I have increased the number of the geometry rendered on the scene, performance of the demo decreased significantly. 😦

Page loading time also increased. I have done a small mistake in my codding, and many of us can face same issue sometime, so thought of sharing to save your time.. 🙂

For example lets say I need to create five cylinders on the scene, The code I have written:

for ( var i = 1; i < 6; i ++ ) {
var cylinderOne = new THREE.CylinderGeometry(14, 14, 120, 25, 25, false);
var cylinder = new THREE.Mesh(cylinderOne, new THREE.MeshNormalMaterial());
cylinder.position.x = 10*i;
scene.add(cylinder);
}

In the above code it is adding five cylinders to the scene. The issue in the code is in the following line:
var cylinderOne = new THREE.CylinderGeometry(14, 14, 120, 25, 25, false);
This line is creating the cylinder object. In the above code we have added this line inside the for loop. So it is creating as many number of objects as we want to render on the scene which increases the page load time.

We ca decrease the page load time significantly just by adding creating the object outside the loop, which will create only one object for one geometry and we can reuse the same object as many times to as we want to render on the scene as follows :

var cylinderOne = new THREE.CylinderGeometry(14, 14, 120, 25, 25, false);
for ( var i = 1; i < 6; i ++ ) {
var cylinder = new THREE.Mesh(cylinderOne, new THREE.MeshNormalMaterial());
cylinder.position.x = 10*i;
scene.add(cylinder);
}

Thats it, 🙂 it will increase your page load time…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s