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?
2
Answers
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 onindex
.push
, saving a method call:useVertices[i] = ___
new Array(len)
indices
,vertices
, andTHREE.Vector3
const
foruseVertices
if you can(Note: Plat00n tried using an array instead of a
Map
above, but even with theget
andset
method calls, theMap
was faster.)You can use – Vectorized approach
Use typed arrays (Float32Array) directly for useVertices instead of pushing elements individually.
Use vectorized operations like slice and copy to manipulate these typed arrays instead of looping through individual elements.
Leverage vectorized functions provided by Three.js like Vector3.fromArray to directly convert from the vertices array to useVertices.