Lag issue with set_cells_terrain_connect

Godot Version

4.3 beta 3

Question

my game is lagging when the “set_cells_terrain_connect” function is executed. here is the code snippet:

		[...]
		var delay := 0
		var cell_chunk_size := 5

		for i in range(0, terrain_cells.size(), cell_chunk_size):
			var chunk = terrain_cells.slice(i, i + cell_chunk_size)
			if chunk.size() < cell_chunk_size:
				var last_value = chunk[chunk.size() - 1]
				while chunk.size() < cell_chunk_size:
					chunk.append(last_value)
			layer.set_cells_terrain_connect(chunk, 0, terrain)
			delay += 1
			if delay >= int(chunk_size.x / delay_time):
				await get_tree().create_timer(.005).timeout
				delay = 0
	return true

this function is used in my case to layer terrain on top of other blocks that are quite common in my game (water). if I replace set_cells_terrain_connect with set_cell there is no lag, but I need terrains especially in this case.

I tried different values ​​of cell_chunk_size but it’s still lagging. smaller values ​​cause a longer but less intense lag, and larger values ​​cause a shorter but more intense lag.

any tips on how to fix or optimize this? thanks!

You can use a Thread to compute this in the background, it might get a little complicated tho if this has to happen during the game