What is more optimized?

Hello! I want to make a shop for my simulator game and i need to acces the clicked item data but first i would like to know which one of those 2 scripts are more optimized :
1 :

local Storage = {}

Storage.Items = {
	{
		Name = "First Item",
		Price = 15
	},{
		Name = "Second Item",
		Price = 25
	}
}

function GetItemPrice(Name:string)
	local ItemPrice = nil
	for _,i in pairs(Storage.Items) do
		if i.Name == Name then
			ItemPrice = i
			break
		end
	end
	return ItemPrice
end

local itemPrice = GetItemPrice("Second Item")

2 :

local Storage = {}

Storage.Items = {
	{
		Name = "First Item",
		Price = 15
	},{
		Name = "Second Item",
		Price = 25
	}
}

local itemPrice = Storage.Items[2].Price

the second script would be faster but these do different things; two things i can suggest though for the first script is…

  • getting rid of pairs entirely for the for loop (for i,v in array do ... end; this has a slight performance increase and makes your code far simpler
  • getting rid of the ItemPrice variable and replacing the ItemPrice = i; break with just return i since that also terminates the loop

with these two optimisations you’ll end up with this:

function GetItemPrice(Name:string)
	for _,i in Storage.Items do
		if i.Name == Name then
			return i
		end
	end
end
1 Like