Any way to optimize my object serializer?

I recently created a simple object serializer which stores objects in datastore’s. I am wondering if there is anyway to optimize my script. Here is the code (you can also find the post that has more info on it here):

-- Services
local players = game:GetService("Players")
local replicatedStorage = game:GetService("ReplicatedStorage")
local dataStoreService = game:GetService("DataStoreService")
local httpService = game:GetService("HttpService")
local dataStore = dataStoreService:GetDataStore("Example_Serialize_System")

local serializeE =

local location = workspace.Plot.plane.itemHolder

local dataLoaded = false
local tries = 3

local rad = math.rad
local cframe =
local angles = CFrame.fromEulerAnglesXYZ
local vector3 =
local color =

-- Saves models currently placed on the plane/plot
local function serialize(plr)
	if dataLoaded then
		local key = plr.UserId
		local data = {}
		-- Saves properties from all objects
		for _, objs in pairs(location:GetChildren()) do
			for i, obj in pairs(objs:GetDescendants()) do
				if obj:IsA("BasePart") then
					table.insert(data, {
						-- p = position
						["p"] = {obj.CFrame.X, obj.CFrame.Y, obj.CFrame.Z, obj.Orientation.X, obj.Orientation.Y, obj.Orientation.Z};
						["s"] = {obj.Size.X, obj.Size.Y, obj.Size.Z}; -- s = size
						["c"] = {obj.Color.R, obj.Color.G, obj.Color.B}; -- c = color
						["n"] = obj.Name; -- n = name
						["t"] = obj.Transparency;
						["mdlN"] = objs.Name; -- t = transparency
						["m"] = string.sub(tostring(obj.Material), 15, string.len(tostring(obj.Material))); -- m = material
						["isPri"] = objs.PrimaryPart == obj; -- isPri = isPrimaryPart
						["f"] = objs:GetDescendants()[1] == obj -- f = firstObject
		local count = 0
		local success, err
		-- To prevent errors and data loss
			success, err = pcall(function()
				dataStore:SetAsync(key, data)
			count = count + 1
		until success or count >= tries
		if not success then
			warn("Failed to serialize data: Error code " .. tostring(err))

-- Loads the data back into the game
local function deserialize(plr)
	local key = plr.UserId
	local serializedData
	local count = 0
	local success, err
		success, err = pcall(function()
			serializedData = dataStore:GetAsync(key)
		count = count + 1
	until success or count >= tries
	if not success then
		warn("Failed to read data: Error code " .. tostring(err))
	if serializedData then
		local model
		-- Loads data
		for i, data in pairs(serializedData) do
			-- Makes sure a model is created only per model
			if data.f then
				model ="Model")
				model.Name = data.mdlN
				model.Parent = location
			local part ="Part")
			part.Anchored = true
			part.CFrame = cframe(data.p[1], data.p[2], data.p[3])*angles(rad(data.p[4]), rad(data.p[5]), rad(data.p[6]))
			part.Size = vector3(data.s[1], data.s[2], data.s[3])
			part.Color = color(data.c[1], data.c[2], data.c[3])
			part.TopSurface = Enum.SurfaceType.SmoothNoOutlines
			part.BottomSurface = Enum.SurfaceType.SmoothNoOutlines
			part.LeftSurface = Enum.SurfaceType.SmoothNoOutlines
			part.RightSurface = Enum.SurfaceType.SmoothNoOutlines
			part.Name = data.n
			part.Material = Enum.Material[data.m]
			part.Transparency = data.t
			part.Parent = model
			-- Handles primary parts
			if data.isPri and model then
				model.PrimaryPart = part
				model.PrimaryPart.CanCollide = false
			wait(0.1) -- this can be removed
		dataLoaded = true
		dataLoaded = true

-- calls

	for i, plr in pairs(players:GetChildren()) do

One change you might consider is compressing numbers info Base64. Also, it might be more memory efficient to convert everything into a string. I know that tables for instance have a memory overhead in addition to whatever you put in them. Instead, using the characters “{}” is 2 bytes.

I agree with AstroCode on both points. Base64 instead of decimal for integers is a lot more efficient as the integers get stored in string form.

I also would make it a string instead of a table, especially as you have it as an array of objects, and just use a single character delimiter, e.g. ; between each array item to use string.split on later when decompressing the data.

Finally, keys like isPri and mdlN is a waste of characters. You’ve got other chars available so I’d use them.

I’m not convinced by this. Using a base64 string instead of a number already adds two extra characters (opening and closing quotes).

For integers, a base 64 representation (as opposed to base 10) only starts being more space efficient for integers greater than 99999. Using a base-64 encoded floating-point format also wouldn’t be especially helpful because every single-precision float (4 bytes) would be expanded out to 8 characters anyway.

Once saved in a Datastore, the data is converted into a string representation anyway. The overhead for tables is minimal (a few bytes). This means that converting the data to a string and adding delimiter characters etc. offers no benefit in terms of conserving space, because you’re just adding your own overhead of the same size. You can check this by looking at a JSON-encoded version of the data.

I think the main thing you can do is tailor your saving/loading system to the requirements of your game/project. It’s very unlikely that you actually need to save all of these properties of every part in a certain area.

I noticed you linked to a general model serializer - in which case you would need store a lot more information about arbitrary parts - but I think this just indicates that a general solution for saving data isn’t ever going to be optimal.

For example, a game where you can place down pre-existing objects should not be saving every property of every part of each placed object; it should be saving the names of the objects placed down and the position/rotation, if applicable.


Depends on the data, especially the nested tables with string keys here (each key being 3 times the bytes needed for a single character key once encoded with quotes). Personally I found on my city building game I reduced the byte count by nearly 1/3 by making it a single string with smarter keys and delimiters than when it was JSON encoded straight from it’s table form.

Also base64 doesn’t add extra opening and closing characters if it’s already a single string, which is why that was preferable in my case over representing coordinates as vectors of decimals. I agree if it’s still in table form, representing as a base64 string instead of a literal number worsens it in many cases. My recommendations from personal experience were to be considered in conjunction with one another rather than separately.

If anyone's curious how much I save with a few other tips:


  • Lua table encoded straight to JSON.
  • Single character keys, similar to the post example.
  • All numbers and integers left as literal numbers and integers. All booleans left as literal booleans.
  • Coordinates represented by tables of 2 entries (as Vector2 does not encode).
  • 2,151 bytes in total.


  • Single string compressed using my own delimiters and built-in assumptions about given items (i.e. what sircfenner said about tailoring the system to the requirements of your project).
  • Values that are equal to the default (e.g. a coordinate placement of 0 in either x or y, default rotation, 0 citizens in the building, 0 workers, etc.) omitted entirely - you can spot these by places where two vertical bars are next to each other, or where there is no data between a bar and a colon or semicolon.
  • All integers encoded to a base 64 numbering system where the integer number can exceed 9. Where integers are used as enumerators with no more than 10 items, they are kept as decimal.
  • All booleans converted to 0 and 1.
  • Same single character keys, unchanged from the “before” table.
  • 810 bytes in total.

This is of course one specific example, but even in the absolute worst case of no default values to omit from the data, it still reduces the byte count quite a lot. I haven’t encountered any cases where the byte count is the same or higher.

No benefit from defaults: 992 bytes total
  • 992 bytes total.

The % benefit decreases slightly as the number of buildings and roads represented in the datasave increase, and likewise the benefit increases as larger integers are used where only one base 64 character is needed. There is still a consistent benefit per building of 50-60%.

That said, there are still things you can do to make your storage smarter, so I agree just making it a string and converting some numbers isn’t enough. Consider what is essential, vs what can be calculated/inferred. Consider default values and only saving things that are non-default.

Another point to consider is if I have a house type called Small House and the user has placed 10 of these around the map. It’s not great to save it as 10 discrete items in your array, instead each item could have the ability to provide an array for each item inside it, which will save you bytes for every clone in the user’s save file. I don’t personally do this as my compression is good enough that the user runs out of land + all available expansion areas before they can possibly fill their datasave, even in the worst case, most densly-packed city possible, with all non-default values.

1 Like