Thread Tools Display Modes
07-01-07, 03:56 PM   #1
Strife[CUK]
A Deviate Faerie Dragon
AddOn Author - Click to view addons
Join Date: Oct 2006
Posts: 10
tostring() leaks memory

Hello All,

A quick question on tostring() and string.format()
I have noticed when doing something like
local var1,var2

function called_onevent_unithealth_changed()
var2=0
var1="text"..tostring(var2)
end
this cause the memory usage to increase.

if it is changed to
...
var2="0"
var1="text"..var2
...
the memory remains static.

Has anyone come across this?
I have tried using string.format() but this has the same affect.
I tried local tostring=tostring outside the function.. didnt help.

Anyone come across this? right now I cant think of an easy workaround and hoping someone has one.

Cheers
  Reply With Quote
07-01-07, 07:16 PM   #2
Tekkub
A Molten Giant
 
Tekkub's Avatar
AddOn Author - Click to view addons
Join Date: Dec 2005
Posts: 960
Every time you create a new string you have to allocate memory. Equal strings share the same memory though. So...

Code:
-- Assume each block here is called independantly, not in order.  
-- If they are called all at once, new strings would not be allocated.
local a, b, c = "a", "b", "c"
local abc = a..b..c
-- This allocates 4 different strings

local abc = "a".."b".."c"
-- This allocates one string

local abc = string.format("%s%s%s", "a", "b", "c")
-- This allocates 5 strings

local x = {}
local m = "m"
for i=1,10000 do
  x[i] = "m"
end
-- This allocates 1 string... but also 10,000 table indexes which might take up a tiny chunk of memory
Smart use of concat (..) is your friend... as does smart use of string.format. Depending on what you're doing each has it's advantage in terms of memory consumption.

As for tostring(), why are you using it in the first place? This works just fine:

Code:
local x = 0
local s = "Blah"..x
The times when you must call tostring are little to none. I personally can't think of a single time I've had to use it.
  Reply With Quote
07-01-07, 07:18 PM   #3
Tekkub
A Molten Giant
 
Tekkub's Avatar
AddOn Author - Click to view addons
Join Date: Dec 2005
Posts: 960
Also, if you're having troubles with concat a nil varaible....
Code:
local x = "Blah"..(this_var_might_be_nil or "")
  Reply With Quote

WoWInterface » Developer Discussions » General Authoring Discussion » tostring() leaks memory


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off