I present you this, which is hybrid of 1 and 2
var grid = {}
func read(x, y):
if !grid.has(x) || !grid[x].has(y):
return null
return grid[x][y]
func write(x, y, d):
if !grid.has(x):
grid[x] = {}
grid[x][y] = d
Explain
- {}
is Dictionary
object, of course dictionary is take a bit more memory than array if it is about same size; but in this case, dictionary would use far less memory than array in (1) because it will contain far less data.
- Dictionary.has()
is the function that loop dictionary object; if it is found the key that match, it will break the loop and return true
, overwise return false
.
- These 2 functions mostly loop x axis of grid object, which the number of object that store in grid object is not much, so it have better performance than (2).
- At line 4 if !grid.has(x)
return true
, it will ignore !grid[x].has(y)
, so it is just loop only the x axis of grid object.
- Even this can rewrite data, I didn't provide how to remove data properly. You can't just simply write null
. If you use as is, it may be a lot of garbage data leftover. Do some research and implement it yourself.