Memory management of textures in B3D...

Blitz3D Forums/Blitz3D Programming/Memory management of textures in B3D...

alain(Posted 2010) [#1]
Hi there,

I did this morning a test program to investigate a memory leak on one of my product.

The program load a new texture on each frame, assign it to a cube, and never delete the old texture (to simulate the possible memory leak).

Looking to the available video memory: it never decrease!

I don't understand why? for me, in Blitz3D, when you do a LoadTexture() it will put the image in memory and when you do a FreeTexture() it will free that memory... But, to my knowledge there is no garbage collector that automatically free the items without any references (like my texture)

Here is the program:
Graphics3D 640,480,32,2
SetBuffer BackBuffer()
camera=CreateCamera()
PositionEntity camera,0,0,-3

cube = CreateCube()

i = 0
While KeyDown(1)<>True

	t = LoadTexture("test.jpg");
	EntityTexture cube,t
	i=i+1
	RotateEntity cube, MilliSecs()/100,MilliSecs()/150,MilliSecs()/50

	RenderWorld
	PrintMem()
	Text 10,50, "Loaded "+i
	Flip
Wend


Function PrintMem()
	am% = AvailVidMem()
	am = am/1024 ;kb
	If(am<0)
		am = am + 4194304
	EndIf
	tm% = TotalVidMem()
	tm = tm/1024 ;kb
	If(tm<0)
		tm = tm + 4194304
	EndIf
	Text 10,10,("Total Video Memory [kb]: "+tm);
	Text 10,30,("Available Video Memory [kb]: "+am);
End Function


Can somebody explain me why the memory usage does not increase in my example?


Yasha(Posted 2010) [#2]
Blitz3D can detect when the same texture file is being loaded more than once, and simply use the same internal texture object, in order to save memory, so the above example will never need to engage a garbage collector.

Actually textures are garbage collected, but it doesn't quite work that way. Loading or creating a texture sets the texture's ref count to 1. Every time an entity is textured with it, the count is incremented, and every time something's textured over the old texture is decremented. FreeTexture simply removes the original texture reference - this means that it doesn't actually delete the texture unless its refcount was only 1 (i.e. nothing was using that texture). Otherwise, the texture will persist in memory until all the objects using it are freed or textured over.

Last edited 2010