Hello! I’ve been trying to learn optimization, and with a new game I’m working on it is a major factor. However, I believe I am too obsessive over memory and tables rather than performance.
As an example, this is how I’d normally store tables for each player or creature:
local dataTable = { Level = 100, Upgrades = { Strength = 1, Health = 2, } }
However, I had the idea to store like this instead, where you’d have to encode (therefore taking less memory):
Is this a good approach? I looked for other people who did this, and asked AI. The answer I got was that it’s not a good thing since it takes up performance to sort of decode this data. But what do you guys think? Thanks!
You shouldn’t be worried about memory usage like that. Your game’s assets are more likely to be a problem than one measly table.
What you’re doing is sort of similar to bit-packing in lower-level languages, but Roblox uses double-precision floats instead of integers, so the cost of synthesizing and reconstructing the values would not be worth it.
For what it’s worth, you can use buffers and/or string.pack/unpack to pack data like this together, but your case doesn’t require it. This is more for serializing data for remotes and datastores.
-- 4 bytes, 2 bytes for each unsigned 16-bit integer local Upgrades = buffer.create(4) -- offset starts at 0, not 1 buffer.writeu16(Upgrades, 0, 1) buffer.writeu16(Upgrades, 2, 2) local Health = buffer.readu16(Upgrades, 2)
Ah okay, thanks so much! Well I should have specified, but I was mostly worried about datastore storing these tables.
I’ve looked into buffers, as much as one video, and they seem useful, I didn’t know they could be used for datastores. I’ll look into those some more and figure out if it’s necessary with ProfileStore. Thank you!
Yeah, just a word a caution: You can’t save buffers directly to datastores because they only allow strings. Doing buffer.tostring will corrupt the data because it’ll try to convert the bytes directly into character codes (0 will become '\0 which is the nul-terminating character`).
What you can do instead is use HttpService:JSONEncode/JSONDecode, which’ll convert the buffer into a JSON string that’s contents are compressed with Base64 or ZSTD (depending on the buffer size). It’s safe to send a raw buffer over a remote, though.