Hi guys, I have an issue with lag spikes due to player inventory size (unique assets).
I have this function below which calculates a players rap and returns the value. To keep the value current i must run it constantly when the value is changed. However this causes a big lag spike if the player has many unique items in there inventory.
I have tried adding a wait() when calling the function which somewhat works although it just delays the lag spike. Is there a better way to obtain these values without the need to loop thru all the players assets and return the calculation?
local rap, pValue = calculateRap(playerData.Assets)wait(5);
This is the function who causes the lag spikes
function calculateRap(assets)
local rap = 0;
local value = 0
for index = 1, #assets do
local item = assets[index];
local price = (item.AveragePrice)
if not price then
price = 0
end
rap = rap + (price * (item.Amount or 0))
local iValue = (item.Value or 0)
value = value + (iValue * (item.Amount or 0))
end
return rap, value;
end
There are around 5000 assets in total in the game, but the lag spikes begin when a player has around 300 unique assets in there inventory… The function is only checking a players unique assets.
Price is calculated by asset.Price * asset.Amount
AveragePrice is just the name given to the assets price or value. (item.AveragePrice) Its not actually averaging anything.
Well if its looping through 300 unique assets without a wait, lower end devices might have small lag spikes. But I don’t think you would want to yield the loop.
You havent got a wait() so calculating it might cause some lag, so if you are running it 300 times. The server will run it 300 times as fast as possible with no regard to memory usage.
Adding the smallest of waits can make a difference in this. If this means that it takes a second to load then you could create a gui progress bar for this. This way you arent sacrificing play ability for a simple function. So long as you let the player know its being calculated and give them a rough idea of progress / how long it will take then it should be fine.
How about you just update the value instead of recalculating? When you add or remove an item just add/subtract it’s value from the total. Then you don’t have to loop through all the items.