I have to fill an array with a lot of objects. My current Implementation is this:
let useVertices = [];
const len = this.indices.length;
for(let i = 0; i < len; i++){
let index = this.indices[i]*3;
useVertices.push(new THREE.Vector3(
this.vertices[index],
this.vertices[index+1],
this.vertices[index+2])
);
}
this.indices
is an Int32Array with a length of almost 4 million.
this.vertices
is a Float32Array with a length of about 650,000.
The implementation shown above takes between 500 and 800 ms.
The Browser I am using is CefSharp, because the website is run in a C# application.
Is it possible to increase the speed of this code?
Gathering together what I think are the best suggestions from the comments (other than frame challenges) pending your testing them:
THREE.Vector3
instances. We can reuse instances instead, remembering previous ones based on index
.push
, saving a method call: useVertices[i] = ___
new Array(len)
indices
, vertices
, and THREE.Vector3
const
for useVertices
if you canconst { indices, vertices } = this;
const V = THREE.Vector3;
const len = indices.length;
const useVertices = new Array(len);
const vectors = new Map(); // For reusing vectors
for (let i = 0; i < len; i++) {
let index = indices[i] * 3;
let vector = vectors.get(index);
if (!vector) {
vector = new V(
vertices[index],
vertices[index + 1],
vertices[index + 2]
);
vectors.set(index, vector);
}
useVertices[i] = vector;
}
(Note: Plat00n tried using an array instead of a Map
above, but even with the get
and set
method calls, the Map
was faster.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With