Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the array size matter in javascript in this case?

I'm creating an array in javascript using item id's from the database whenever a corresponding button is clicked on the page. Each array entry will store a custom object.

The id's from the database for a specific can start from any number like 80123 to 80223, for that specific page of data.

so the first entry in the array will be like arr[80123].

Now when i check the length of the array it shows me 80123 ! even though theres only 1 element in it, i thought of using associative or character indexed arrays, but they lack some basic sorting operations that i would need.

Now my question is "How much memory will the array actually be consuming if there is only 1 element in it but the length of the array is 80123 ?"

More info...

The base number keeps changing 80123 is only an example.

the code im using is as follows:

function ToggleAction(actionButtonID, action) 
    {
        var extractedID = ExtractNumericIdFromTag(actionButtonID);
        var arrayIndexer = extractedID; // Can update this to make array associative

        if(actionItems[arrayIndexer] == null)
        {
            actionItems[arrayIndexer] 
                = new ActionItem(extractedID, action);
        }
        else
        {
            var ai = actionItems[arrayIndexer];
            ai.action = action;
        }
    }
like image 303
Storm Avatar asked Sep 22 '09 14:09

Storm


1 Answers

Your code is not allocating that much memory, so you don't have to worry about that. Javascript Arrays are smart enough. However, I still think you should be using an Object instead of an Array in this case...

var num = 80123;
var obj = {};
obj[num] = { Name: "Josh" };

alert(obj[80123].Name);
like image 62
Josh Stodola Avatar answered Oct 21 '22 10:10

Josh Stodola