How can i set 2d array to 0 without for loop?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By MadDevil57
for x in range(array.size()):
	for y in range(array[x].size()):
		array[x][y] = 0

That what i have right now but it’s very inefficient.
This code is running around 4000 times and i want to optimize it.
I would like to do it without for loop, but i have no idea how to do it in GDscript.

:bust_in_silhouette: Reply From: Moreus

For what You use so big arrays? Isn’t default 0?

I don’t have big array, i mean that this for loop is setting array to zero 4000 times.
I have 8x8 array as map, and move array to calculate possible moves on that map(like it can’t go through some tiles and etc.). Basically it set possible coordinates to 1 and imposible to 0.
I have an ai that need to check 4 moves ahead and choose most efficient move. By that it creating around 4000 possible moves for every enemy and player in any possible position on the board. And after it calculates possible moves, array needs to be erased by making it zero.
So my code already optimized enough to handle that in 60 fps without a lag, but i want to get rid of as much loops that i can, just because it’s the most complicated tasks in my code right now.
I think about something like array = [[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0], ...] but not sure if it would be faster than loop.

MadDevil57 | 2023-03-18 09:45

you can save array_zero for later ad just copy array_zero when needed clean, still array of 64 size or two 8x8 should be instant

Moreus | 2023-03-18 14:44

you can use void resize ( int size )

Moreus | 2023-03-18 14:51

:bust_in_silhouette: Reply From: Ktwru

What about

for x in array.size():
    array[x].fill(0)

?

Your solution turns out to be the best one

MadDevil57 | 2023-03-20 13:01

:bust_in_silhouette: Reply From: MadDevil57

Checked all answers and compare them.

for x in range(array.size()):
		for y in range(array[x].size()):
			array[x][y] = 0

My code calculate 2000x2000 array in 483 msec.

for x in array.size():
		array[x].fill(0)

This code calculate in 14 msec.

#after creating empty array just copy it to other array
array_zero = array.duplicate()

#then copy to main array
array = array_zero.duplicate()

And this code is the best and the calculation is done instantly: 0 msec.
But for some reason if last code executed many times the game just crashes, so i’d recommend using second solution.
Thanks to Ktwru for best solution, and everybody who tried to help!

:bust_in_silhouette: Reply From: godot_dev_

yourArrary.clear() will zero (remove everything) the array, making it an empty array