I have an array of elements like this:
myArray = [{name:'john',age:25},
{name:'marta',age:20},
{name:'pedro',age:22}]
My program has to access an object by it's name several times a second. I defined this function:
function getPersonByName(name){
for (var i=0; i<myArray.length; ++i)
if (myArray[i].name == name)
return myArray[i]
}
var john = getPersonByName('john');
But that loop running everytime seems inneficient. I could instead create a hash table associating the objects, and keep it updated:
var hash = {john:myArray[0], marta:myArray[1], pedro:myArray[2]}
var john = hash["john"]
But I don't know how the javascript's hash access is defined, so, is the second method actually faster?
std::map, which uses red black trees. So it'sO(log N)instead ofO(N), and that's, as Pointy said, much, much, much faster.