Memory paranoid question.

Hi.
For example. I have a bunch of lua files where each file represents single inventory item, kinda like in PointShop

inventory/coffee_cup.lua



local tbl = {
	name = "Coffee cup",
	price = 150,
	onUse = func,
	category = "food",
	...etc,
}
inventory.registerItem(tbl)


So in the method inventory.registerItem I’ll proccess this data.
But for example if I have 50 food items and each of them has “category” field with the same string “food”, but it actually different strings, memory n stuff.
Is that worth to worry about?
Mb there’s a way to optimize this thing?

if you really are concerned about this couldnt you just have 1 variable. Variables is references and internally they are accessed via pointers so just have category = foodVar or something

Yea, I thought about this, but damn, it looks shitty.

I have an idea, not sure if it will work.

Look:

  1. Let every item tbl to has their own category string.
  2. Process tbl and compare category value with some table (catTbl) which contains all existing categories.
  3. If that (catTbl) has no this particular one, add it and assign catTbl’s value to our item’s table category field.
  4. Now item.category = catTbl[n] = “food”
  5. Old item.category now unaccessable from Lua
  6. Gargage collector does his job

???




inventory = {
	registerItem = function(tbl)
		if table.hasValue(inventory.catTbl, tbl.category) then
			table.insert(inventory.catTbl, tbl.category)
		end
		tbl.category = inventory.catTbl[table.KeyFromValue(inventory.catTbl, tbl.category)]
		table.insert(inventory.items, tbl)
	end,
	catTbl = {},
	items = {},
}

local tbl = {
	name = "Coffee cup",
	price = 150,
	onUse = func,
	category = "food",
	...etc,
}
inventory.registerItem(tbl)




If you are creating 50 item types and they never change, you don’t have to worry about memory.

Memory would (maybe) become an issue if you were doing something thousands of times over and over again in a loop.

Time to get way too technical with LuaJIT again to answer a simple question I guess.

So, LuaJIT is really smart. It seems to pre-hash all the strings it deals with, and it will bail out of string creation if a string already exists. Link

Even if the above wasn’t the case, I suspect LuaJIT’s prototype tables would reference the same string internally.

Note that I may be entirely wrong, but even if this wasn’t the case, ph:lxyz is right. You aren’t going to run out of memory when dealing with user defined tables.

Seems similar to truth :slight_smile:

Thanks a lot :slight_smile: