miércoles, 11 de septiembre de 2013

Storing values as object properties instead of creating a values array

Im working on a project were I'm storing values and building a table with that data, as there are three groups of data, each combination (group1, group2, group3) is identified with an id.
As the combinations can be regenerated multiple times, or new ones can be added, I needed to store the ids in a data structure, to check wether I should or must not add the combination if I already have it.

Storing the ids inside an array not convinced me because didn't want to walk the array multiple times searching for ids, so what I did was to create an object, and store the ids as properties of the object:

combinationsIDs = {
       id1: true,
       id2: true
       .........   
}

So, what I do is to check if the property exists, using the typeof operator. If it exists then the combination exists so I don't add the combination, if it doesn't exists then I add the combination and add the id as a new property to my combinationsIDs object.

I've added a jsPerf test case, comparing the solution proposed here against array.indexOf, results were 30% faster.

http://jsperf.com/searching-inside-array-vs-object-v2

Seems to be a simple and reliable solution, What do you think?

No hay comentarios:

Publicar un comentario