Optimization: using 'if' to detect input VS updating the variable constantly

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By LiesLiesLies

Hi, I’m new here and would really like some help here, I have made 2 functions to get the player input, one of them uses a lot of ‘if’ statements, like you can see in the learn section of Godot, and the other one was made with the intention of not using any ‘if’ statements, I’ll add the code down below, if anyone with knowledge on the subject could help i would be thankful, does the change make any significant impact in performance?

Code 1:

func get_input():
    rotation += get_local_mouse_position().angle() * rot_speed #1
	velocity = Vector2()
	if Input.is_action_pressed("move down"):
		velocity.y += 1 #2
	if Input.is_action_pressed("move up"):
		velocity.y += -1
	if Input.is_action_pressed("move left"):
		velocity.x += -1
	if Input.is_action_pressed("move right"):
		velocity.x += 1
	velocity = velocity.normalized() * speed #3
	if Input.is_action_just_pressed("Fire"):
		shoot()

Code 2:

func get_input():
	rotation += get_local_mouse_position().angle() * rot_speed
	velocity.x = (Input.get_action_strength('move right') - Input.get_action_strength('move left'))
	velocity.y = (Input.get_action_strength('move down') - Input.get_action_strength('move up'))
	velocity = velocity.normalized() * speed
	if Input.is_action_just_pressed("Fire"):
		shoot()
:bust_in_silhouette: Reply From: kidscancode

Write code you can read and understand. The code in the examples is written the way it is because it’s clear and readable. Your change just results in extra long lines that wrap. There is going to be no measurable difference in the two snippets.

This is a solution to a problem that doesn’t exist. Performance is not something you should be thinking about when it comes to a few lines of input. You should not try to optimize something that doesn’t need it. IF you’re experiencing performance problems with your game, you need to profile it to find where the source of the slowdown is.

Just write your code. Worry about performance when you actually have a problem.