How to optimize this code

Godot Version

Godot 4.3 dev1


Hey y’all, i’m making a interaction system and i want to give weight to my objects to slow down the player when he grabs it. I’m kinda worried with my code, so i want to make it more “optimized”, if you understand me.

Here is my code so far:

func slow_player(item_properties):
	var decrease_ammount = 0.0
	if item_properties.Weight > 0.0 and item_properties.Weight <= 3.0:
		decrease_ammount = 0.15
	elif item_properties.Weight > 3.0 and item_properties.Weight <= 8.0:
		decrease_ammount = 0.25
	elif item_properties.Weight > 8.0 and item_properties.Weight <= 10.0:
		decrease_ammount = 0.5
	elif item_properties.Weight > 10.0 and item_properties.Weight <= 30.0:
		decrease_ammount = 0.7
	elif item_properties.Weight > 30.0:
		decrease_ammount = 0.8
	SPEED -= decrease_ammount

I created a Resource called “item_properties” and assined some properties (like Name, Weight, Type, Position, etc), all i want to do is: if the item is heavy, the player slows down

I think it might be helpful for you to go into more detail about what you mean by optimization. As far as CPU usage, the code you’ve shown will be very fast. At worst case, you have eight comparisons, one addition operation, and three assignments, all of which should run in a matter of nanoseconds, if not less - definitely not something worth worrying about optimizing.

There’s a couple of minor tweaks you could do to reduce the number of comparisons you’re doing, but I’d encourage you to think about whether you might be engaging in premature optimization. Whenever you optimize code for performance, it generally comes at a cost – most commonly time and readability. Readability is important because it affects how likely you are to accidentally add a bug and how easy it is to find that bug once you’ve added it. In general, more readable code tends to also be more bug-resistant.

Does that help?

1 Like

That helps! I’ll try to study more about optimization in Godot. I switched from Unity to Godot, so i started studying it, but i never tried to make my projects more optimized.

1 Like

Glad I could help! My biggest tip for optimization is to start with the big picture and then use profiling to narrow your focus to the part which needs optimization the most.

There’s an old rule that says that 99% of the slowdown and inefficiencies in your program are caused by only 1% of your code, and in my experience it’s almost always true. If you can find that 1% and focus on optimizing that part, you can can get huuuuge speedups.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.