Lightweight clone()

I have Factory class which is supposed to return pre-assembled objects composed of various geometric shapes grouped using Object3d. Code is below, it works, but I notice that using clone() is more of a performance hit than just repeatedly redrawing the geometries. Why is that? What am i doing wrong? Example: Create easily spawn-able chess piece:

this.pawn = new THREE.Object3D(); // CREATE GROUP 
//ADD VARIOUS GEOMETRY:
var sphere = new THREE.Mesh(
    new THREE.SphereGeometry(4,5,5) ,
    new THREE.MeshBasicMaterial({ color:0x33FF44, wireframe: true }) );
sphere.position.y=22;
this.pawn.add( sphere );
var cyl_height=16;
var cylinder = new THREE.Mesh(
    new THREE.CylinderGeometry( 3, 4, cyl_height, 10 ),
    new THREE.MeshBasicMaterial( {color:0x33FF44, wireframe: true}) );
cylinder.position.y=cyl_height/2;
this.pawn.add( cylinder )
this.pawn.add( circle );
this.avatars['exchange']=this.exchange;
this.avatars['pawn']=this.pawn;
//// USAGE:   getClone('pawn')  --> should return light weight clone of pre-built ?
this.getClone=function( identifier_in ){
    return this.avatars[ identifier_in ].clone();
}

Using Object3D.clone() means you perform object creation, which is in general a relatively expensive operation in JavaScript. Especially if you do this per frame and perform a deep/recursive clone which is the default behavior of Object3D.clone() (meaning the method also clones the entire hierarchy of child objects). Because of this, it’s in general more performant to reuse objects if possible.

1 Like

I’m only using clone() when I need multiple copies simultaneously on screen at once, and only 1 time upon loading data. Is there more efficient way to do this?

Your performance problems might be related to too many draw calls. You can try to merge the geometries into a single one or use instanced rendering. The latter one is ideal if you have many objects of the same geometric type just with different transformation.

Related: How to optimize objects in three.js? Methods of optimization