开发者

What's the fastest way to keep an ordered map in javascript?

开发者 https://www.devze.com 2023-01-13 09:36 出处:网络
I开发者_如何学JAVA use a javascript object as a map. Let\'s say I populate it like this: for (var i=0;i<100;i++) {

I开发者_如何学JAVA 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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号