views:

43

answers:

1

I use a javascript object as a map.

Let's say I populate it like this:

for (var i=0;i<100;i++) {
   var key = "A"+(i%10);
   oj[key] = i; 
}

This creates a map with 10 keys. The value of 100 and 10 are just fictitious. it could be 10000 events which create a map of 3000 or similar.

I now want to print the map alphabetically:

//
// First I transfer the items in an array.
// 
array = []; 
for (var i in oj) {
    array.push(i); 
}

//
// then I sort them
//
array.sort();

//
// now I can process them
// 
str = '';
for (var i=0;i<array.length;i++) {
   str+= array[i]+' '+oj[array[i]]+'\n'; 
}

Can anybody suggest a better* way ?

*better meaning faster !!!

Thanks a lot

+1  A: 

Since you're creating the map, you can simultaneously create the sorted list (in sorted order). This would prevent both the array creation and the sorting at the times when you want to display them. You would end up trading memory for speed, but that is normal in performance tuning.

If you can't do the above all up front, consider sorting when you insert. Depending upon the sort implementation, that could save time.

John Fisher
Adding items in sorted order would be too expensive. Wouldn't it ? please try it out and you will see for yourself.
Lx1
@Lx1: Your example shows them being added in sorted order. What would be expensive about simply adding them to an array, too?
John Fisher