I need help with code optimization and its variations. Please provide examples of code optimization, for example:
-- Not optimized code
local function calculate_sum(a, b)
local sum = 0
for i = a, b do
sum = sum + i
end
return sum
end
local result = calculate_sum(1, 100000)
print(result)
and
-- Optimized code
local function calculate_sum(a, b)
return (a + b) * (b - a + 1) / 2
end
local result = calculate_sum(1, 100000)
print(result)
It will be interesting for me to read all your codes and scripts in an unoptimized and optimized version. We can also discuss everything related to code optimization, logic simplification and compression here.
again:
-- Not optimized code
local players = game:GetService("Players")
local replicatedStorage = game:GetService("ReplicatedStorage")
local playerGui = players.LocalPlayer:WaitForChild("PlayerGui")
local function onButtonClicked(button)
if button.Name == "BuyButton" then
local playerMoney = replicatedStorage:WaitForChild("PlayerMoney"):GetValue()
local itemPrice = button.Parent:WaitForChild("Price"):GetValue()
if playerMoney >= itemPrice then
playerMoney = playerMoney - itemPrice
replicatedStorage:WaitForChild("PlayerMoney"):SetValue(playerMoney)
local itemId = button.Parent:WaitForChild("ItemId"):GetValue()
replicatedStorage:WaitForChild("Inventory"):WaitForChild(itemId):SetValue(true)
playerGui:WaitForChild("InventoryGui"):WaitForChild(itemId):WaitForChild("OwnedImage").Visible = true
button.Parent:WaitForChild("BuyButton").Visible = false
button.Parent:WaitForChild("BoughtImage").Visible = true
end
end
end
for _, button in pairs(playerGui:WaitForChild("ShopGui"):GetChildren()) do
if button:IsA("TextButton") then
button.MouseButton1Click:Connect(function()
onButtonClicked(button)
end)
end
end
and
-- Optimized code
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local PlayerGui = Players.LocalPlayer.PlayerGui
local InventoryGui = PlayerGui.InventoryGui
local Inventory = ReplicatedStorage.Inventory
local PlayerMoneyValue = ReplicatedStorage:WaitForChild("PlayerMoney")
local ShopGui = PlayerGui:WaitForChild("ShopGui")
local function OnButtonClicked(Button)
if Button.Name == "BuyButton" then
local Item = Button.Parent
local ItemId = Item.ItemId.Value
local ItemPrice = Item.Price.Value
local PlayerMoney = PlayerMoneyValue.Value
if PlayerMoney >= ItemPrice then
PlayerMoneyValue.Value = PlayerMoney - ItemPrice
Inventory:WaitForChild(ItemId).Value = true
Item.BuyButton.Visible = false
Item.BoughtImage.Visible = true
InventoryGui:WaitForChild(ItemId).OwnedImage.Visible = true
end
end
end
for _, Button in ipairs(ShopGui:GetChildren()) do
if Button:IsA("TextButton") then
Button.MouseButton1Click:Connect(function()
OnButtonClicked(Button)
end)
end
end
Waiting for your stories and code