Skip to content

Commit 93d5df5

Browse files
authored
perf(obj-serializer): improved performance by using Map for unique vertices
1 parent b138b6e commit 93d5df5

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

packages/io/obj-serializer/index.js

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,8 @@ const serialize = (options, ...objects) => {
6969
// construct the contents of the OBJ file
7070
let body = '# Wavefront OBJ file generated by JSCAD\n'
7171

72-
// find unique vertices
73-
const vertices = []
72+
// find unique vertices - use Map for O(1) lookup instead of O(n) indexOf
73+
const vertexMap = new Map() // vertex string -> index (1-based)
7474

7575
// convert objects
7676
// TODO: group objects together
@@ -86,9 +86,10 @@ const serialize = (options, ...objects) => {
8686
polygons.forEach((polygon) => {
8787
polygon.vertices.forEach((vertex) => {
8888
const vertexString = convertVertex(vertex)
89-
if (vertices.indexOf(vertexString) < 0) {
89+
if (!vertexMap.has(vertexString)) {
9090
// add unique vertices
91-
vertices.push(vertexString)
91+
const index = vertexMap.size + 1 // OBJ uses 1-based indexing
92+
vertexMap.set(vertexString, index)
9293
body += `${vertexString}\n`
9394
}
9495
})
@@ -99,7 +100,7 @@ const serialize = (options, ...objects) => {
99100
polygons.forEach((polygon) => {
100101
// convert vertices to indices
101102
const indices = polygon.vertices
102-
.map((v) => vertices.indexOf(convertVertex(v)) + 1)
103+
.map((v) => vertexMap.get(convertVertex(v)))
103104
// set face color
104105
const color = getColorName(polygon) || objectColor || 'default'
105106
if (color !== previousColor) {

0 commit comments

Comments
 (0)