How to improve if statements performance

Hi so for my game i’ve created a webbrowser in which your able to type a url and the corresponding website will appear.
Here is a snip of the script

local box = script.Parent
box.FocusLost:Connect(function(enterPressed) 
    if box.Text == "test" then
	       print("lol")
	elseif box.Text == "test2" then
		print("lol2")
	end
end)

Is there anyway to improve the performance of this script. Since right know its need to check each website if its each website which could slow down performance a lot. The finished script will contain around 65 different websites. Kind of new to scripting to i don’t know a lot of the more complicated scripting concepts. If anyone has a method for improving this that i’m not aware of then please share it.

1 Like
local box = script.Parent

local websites = {
	"website1";
	"website2"
}

box.FocusLost:Connect(function(enterPressed) 
	if websites[box.Text] then
		print(website[box.Text])
	end
end)

Of course for functioning sites that are interactable, you can do this instead:

local box = script.Parent

local websites = {
	["website1"] = function()
		print("lol")
	end;
	
	["website2"] = function()
		print("lol2")
	end
}

box.FocusLost:Connect(function(enterPressed) 
	if websites[box.Text] then
		websites[box.Text]()
	end
end)
4 Likes

Worth noting the first solution won’t work as the website name is the value and the code checks the key.

Probably best to just keep the second solution in the post.

2 Likes

I used the second one to.

(30 char)

This script is performant enough, please do not practice premature optimizations.

As a matter of fact, for readability, I suggest if-elseif statements for matching a list of discrete values the variable could be. Although it may seem repetitive, it’s far easier to maintain than a mapping of functions and values (and, if you’re paranoid about performance, mapping values to functions is slower).

However, if you could show an example of what you do per website entered, perhaps myself or another member of the community can suggest a more programmatic, dynamic solution?

1 Like

Well it mainly just relays on making frames visible and invisible with some animations (done by functions). I just have over 65 websites that needs to be added. Plus also a separate console in which you can enter commands. Plus I just wanna know more about scripting and stuff. I feel like these things could become useful in the future for me. Thanks alot for the help.

Instead of semantically describing it, could you give two different cases that myself or another member of the community can compare?

1 Like