How much memory do strings take?

I’m looking through my code and trying to optimize it as much as possible. I was thinking about putting strings that are used a lot into variables and using those instead of creating thousands of new strings, but is this worth doing or are strings optimized already on a lower level?

Example:

local Attachments = {}

for _, Child in pairs(self.Model:GetDescendants()) do
	if (Child.ClassName == "Attachment") then --Potentially thousands of strings?
		table.insert(Attachments, Child)
	end
end

--OR
		
local Attachments = {}
local AttachmentString = "Attachment" --Is this optimization worth doing?

for _, Child in pairs(self.Model:GetDescendants()) do
	if (Child.ClassName == AttachmentString) then
		table.insert(Attachments, Child)
	end
end

Lua stores constant strings, so your literals are cached. New strings if they’re small enough are also interned, but not a good idea to rely on that.

As for the amount of memory a string takes up, it’s the amount of bytes (#str) plus some metadata such as 4 to 8 bytes for the length and a few more bytes for any other tags and information.

1 Like

Can’t give a better explanation than Autterfly did. But heres some comments on optimization and your example.

In Algorithms you analyze the resources used to determine efficiency/ complexity; which can be run time or space used. But you’ll be most concerned about the run time complexity, and want it to be as small as possible. There are even some algorithms which use ‘Dynamic programming’ to use more memory to achieve faster run times, by memoizing subproblems.

It’s also good to understand how memory works and how memory is stored; because the cache design optimizes retrieving data from memory.

But in your example, it’s good to know how code is compiled. You’ve only specified one literal string in both options of your example, so the first option is going to store that same amount of strings as the second.