0

I am currently making a tile map for a platformer.

I know in other languages, when you refer to a 2 dimensional array, it is faster to do:

world[y][x]

But, in javascript, does it matter? Can you do:

world[x][y]

Thanks for your time.

Lots o Sheeps
  • 85
  • 2
  • 7

1 Answers1

2

First off, Arrays in JavaScript are just specialized objects. So when you have var a = ["entry"] and then go a[0], you are accessing a property of a stored as "0". Since all properties are converted to strings for JavaScript this means a[0] === a["0"]. Unlike in languages such as C++ when creating a double array you have to go darray[y][x] because of how the memory is created, with JavaScript we can assign an object to that location (since it is just another property) such that we can interpret how we want to!

var world = [], // Start out with something empty.
    X = Y = 10; // Get dims.
// Fill that sucker up!
for(var i = 0; i < X; ++i)
{
    var x = [];
    for(var j = 0; j < Y; ++j)
    {
        // Forces a place holder in the array.
        x[j] = undefined;
    }
    world[i] = x;
}

And presto! Now, you can go world[x][y] to get objects stored in those locations. Just as a little bit more information, the place holder is used to make the array actually have a length of Y as well.


Now, let's come back to the fact that an array is just a specialized object. This means we are accessing a property of the object world then again in the entry stored at that location. Therein, the speed of access is limited by how the properties were chosen to be stored (as @zerms pointed out in the comments).

Community
  • 1
  • 1
tkellehe
  • 659
  • 5
  • 11
  • 1
    "Therein, the property is stored in a hash map" --- it makes sense to mention, that the standard does not put any constraints here. So it might be a tree, or an array, up to engine implementors. So in general one cannot state that property access has constant time approximation for any arbitrary implementation. – zerkms Nov 08 '15 at 02:52
  • `// Prevents from duplicating x everywhere. (function(x) { world[i] = x })(x);` --- this code makes no sense. – zerkms Nov 08 '15 at 02:56
  • @zerkms. It is true that ECMAScript standard places no constraints on the implementation, that is my bad. Here is some information on the [access time](http://stackoverflow.com/questions/3858411/whats-the-big-o-for-javascripts-array-when-used-as-a-hash). Sorry, about that... I pulled that from some code I used from a terrain sim where I needed to prevent `x` from being the same object in every entry. Let me try this again, I did that from my phone lol – tkellehe Nov 08 '15 at 03:22