DataStore2 Optimization Help

hello I just made some scripts work, however I’ve noticed quite poorly performance when the player joins or leaves and idk why exactly, is it this?, if so is there some sort of way to optimize this code?

local dss = game:GetService('DataStoreService')
local cosmetics = game:GetService('ReplicatedStorage'):FindFirstChild('ItemStorage')
local ServerScriptService = game:GetService("ServerScriptService")
local playerService = game:GetService('Players')

local DataStore2 = require(ServerScriptService.DataStore2)

DataStore2.Combine("hatEquipDS", "data")

game.Players.PlayerAdded:Connect(function(player)
	local hatEquipDS = DataStore2("data", player)
	player.CharacterAdded:Connect(function(char)

		local userId = player.UserId
		local data = nil
		local attemptsLeft = 10

		local success, errorMessage
		repeat task.wait()
			success, errorMessage = pcall(function()
				data = hatEquipDS:Get()
			end)
			attemptsLeft -= 1
		until (attemptsLeft == 0) or success

		if (not success) then
			warn("Error Loading player data:", errorMessage)
			return
		end

		if data then
			--//Code
			local inv = player:FindFirstChild('Inventory')

			for _,item in pairs(inv:GetChildren()) do
				for _,files in pairs(data) do
					if files == item.Name then
						
						item:Clone().Parent = char
						print(inv[files])

					end
				end
			end
			
		else
			warn(errorMessage)
		end

		return true
	end)

	player.CharacterRemoving:Connect(function(char)
		local inv = player:FindFirstChild('Inventory')
		local accessoryEquip = {}


		for _,charS in pairs(char:GetChildren()) do
			for _,item in pairs(inv:GetChildren()) do
				if charS.Name == item.Name then
					table.insert(accessoryEquip, charS.Name)
				end
			end
		end

		local userId = player.UserId
		local attemptsLeft = 10
		local success, errorMessage

		repeat task.wait()
			pcall(function()
				success, errorMessage = hatEquipDS:Set(accessoryEquip)
			end)

			attemptsLeft -= 1
		until (attemptsLeft == 0) or (success)

		if success then
			print(player.Name .. "'s "..script.Name.." data was saved successfully!")
		--print(accessoryEquip)
		else
			warn(player.Name .. "'s "..script.Name.." data wasn't saved! :", errorMessage)
		end

		return success, errorMessage
	end)

end)

I’ve a feeling that it might be every time it passes thru

pcall(function()
				success, errorMessage = hatEquipDS:Set(accessoryEquip)
			end)

if you’re smarter than me and know how to find the issue when looking thru the console the game is here:

have fun with new data i give u :]

1 Like

thank you the help, i will make sure to learn and use it properly :smiley:!!