Does a SpriteBatch instance need to call dispose() once it is no longer used? - libgdx

According to this article, a SpriteBatch instance needs to call dispose() once it is no longer needed. However, as I examine some of libgdx's official examples like Pax Britannica and Super Jumper, I found out that they never call SpriteBatch.dispose(). Why is that?

SpriteBatch must always be disposed.
Internally, it creates and manages several Mesh objects. These objects allocate vertex/index arrays on the GPU. Those are only deallocated if you explicitly call Mesh#dispose(), which will be triggered by calling dispose() on your SpriteBatch object.
It will also, by default, create its own ShaderProgram. And similarly, would be leaked if you didn't call dispose().
If the demo's aren't doing this, perhaps it's time to send a pull request!

I think the given demo games try to keep things simple. They are supposed to show how the basic things in libgdx work in a minimalistic way and thus also abstract a little of some details. That's useful for beginners to not bloat up the examples with a lot of very specific code.
In a real world example I think SpriteBatch.dispose() has to be called in the dispose() method of the GameScreen in SuperJumper for example. And also GameScreen.dispose() has to be called when switching back to the MainMenuScreen, because this doesn't happen automatically as well.
When creating a Spritebatch like this new SpriteBatch(), it creates one internal Mesh. When not calling SpriteBatch.dispose() this one mesh would also not be disposed and thus SuperJumper has a memory leak there.

I've created games where I have multiple screens which all has their own SpriteBatch. I just removed all dispose() methods of the batches and for me, there's no effect of this. So keep in mind to check for this before releasing your product. Even if you can't feel any downside not to dispose batches, there's no reason not to dispose them. Just do it on the Screen implemententations dispose methos, takes about 1 nano second to do :)

Related

External FLASH slow verification with STM32cubeProgrammer

I'm working with an STM32F469 chip with a Micron MT25Q Quad_SPI Flash. To program the Flash, there needs to be an external loader program developed. That's all working, but the problem is that verification of the QSPI Flash is extremely slow.
Looking in the log file, it shows that the Flash is being programmed in 150K byte blocks. However, the verification is being done in 1K byte blocks. In addition, the chip is re-initialized before each block check. I've tried this with both through STM32cubeIDE and in STM32cubeProgrammer directly.
The external programmer program include the correct chip configuration information and specifies a 64K page size. I don't see how to get the programmer to use a larger block size. It looks like it understands what part of the SRAM is used and is using the balance of the 256K in the on-board SRAM for programming the QSPI Flash. It could use the same size for reading the data back or use the Verify() function in the external loader. It's calling Read() and then checking the data itself.
Any thought or hints?
Let me add some observations on creating a new external loader. The first observation is "Don't." If you can pick a supported external chip and pin it out to use an existing loader, then do that. STM provides just 4 example programs but they must have 50 external loaders. If the hardware design copies the schematic for a demo board that has an external loader, you should be fine and avoid doing the development work.
The external loader is not a complete executable. It provides a set of functions to do basic operations like Init(), Erase(), Read() and Write(). The trick is that there is no main() and no start-up code is run when the program starts.
The external loader is an ELF file, renamed to "*.stldr". The programming tool looks into the debug information to find the location of the functions. It then sets the registers to provide the parameters, the PC to run the function, and then let's it run. There's some super-clever work going on to make this work. The programmer looks at the returned value (R0) to see if things pass or not. It can also figure out if the function has crashed the core or otherwise timed-out.
What makes writing the external super fun is that the debugger is running the program so there's no debugger available to see what the code is doing. I settled on outputting errors, and encoded information, on the return() from the called functions to give hints as to what was happening.
The external loader isn't a "full" program. Without the startup code, lots of on-chip stuff isn't set up and some just isn't going to work. At least I couldn't figure it out. I'm not sure if it wasn't configured right or the debugger was blocking its use. Looking at the example external loaders, they are written in a very simple way and do not call the HAL or use interrupts. You'll need to provide core set-up functions to configure the clock chains. That Hal_Delay() method will never return as the timers and/or interrupts aren't working. I could never make them work and suspect the NVIC was somehow being disabled. I ended up replacing the HAL_delay() function with a for loop that spun based on core clock rate and a the instruction cycles per loop.
The app note suggests developing a stand-alone program to debug the basic capabilities. That's a good idea but a challenge. Prior to starting the external loader, I had the QSPI doing the needed operations but from a C++ application calling the HAL. Creating an external loader from that was a long exercise in stripping out and replacing functionality. A hint is that the examples are written at a register level. I'm not that good to deal directly with the QuadSPI peripheral and the chip's instruction set at the same time.
The normal start-up of a program is eliminated. Everything that's done before the main() is called (E.g., in startup_stm32f469nihx.s) is up to you. This includes setting the clock chains to boost the core clock and get the peripheral buses working. The program runs in the on-chip SRAM so any initialized variables are loaded correctly. There's no moving data needed but the stack and uninitialized data areas could/should still be zeroed.
I hope this helps someone!
Today I've faced the same issue.
I was able to improve the Verify speed with two simple steps, but Verify still much slower than programming and this is strange...
If anyone find a way to change the 1KB block read of STM32CubeProgrammer I would like to know =).
Follow the changes I made to improve a bit the performance.
Add a kind of lock in the Init Function to avoid multiple initializations. This was the most significant change because I'am checking the Flash ID in my initialization proccess. Other aproachs could be safer but this simple code snippet worked to me.
int Init(void)
{
static uint32_t lock;
if(lock != 0x43213CA5)
{
lock = 0x43213CA5;
/* Init procedure goes here */
}
return(1);
}
Cache a page instead of reading the external memory for each call. This will help more if your external memory page read has too much overhead, otherwise this idea won't give relevant results.

Flex 3 Memory leak issue

We have a huge flex applications using multiple modules. There is a huge memory leak problem over prolonged usage of loading and unloading modules.
Based on all the search and different articles I understand that I need to clean up objects on unload, remove event listeners, stop timers and dispose any references.
I started this by picking up one component at a time within one of the module.
Here is how this is structured.
There is one parent application which loads a module, which has multiple views. The component is defined in mxml and is referenced in the mxml module in a view stack.
This mxml component is a VBox with event listeners added as-
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml"
paddingTop="10"
paddingLeft="10"
paddingBottom="10"
paddingRight="10"
creationComplete="onInit()"
show="onShow()"
resize="onResize(event)" ....
There are couple of properties that are binded from the parent container in mxml. Other than the above listeners there is also a private variable accessed from outside -
[Bindable]
private var _model:SModelLocator=SModelLocator.GetInstance();
On unload of the module I call a dispose function in this component as below-
public function dispose():void
{
this.removeEventListener(FlexEvent.CREATION_COMPLETE,onInit);
this.removeEventListener(FlexEvent.SHOW,onShow);
this.removeEventListener(ResizeEvent.RESIZE,onResize);
var arr:Array = this.getChildren();
for(var i:int = 0; i<arr.length;i++)
delete arr[i];
this.removeAllChildren();
_model = null;
//Properties that are binded from the parent container
Property1 = null;
Property2 = null;
this.deleteReferenceOnParentDocument(this.parentDocument as IFlexDisplayObject);
}
Now when I run profiler and switch between modules number of instances of this component still continues to grow. I clicked on GC Collect on profiler and still the instances stay.
On the parent container which is the module mxml, I also tried writing the following lines upon unload of module-
//function call to invoke dispose as above
component1.dispose();
component1 = null;
Please help. I am not sure what am I missing here, or even if this is the right approach.
Thanks.
This will not solve your problem but I hope it helps.
First and foremost you are not getting anywhere just by looking and refactoring code. You need hardcore data that proves that you have a leak, which then will tell you what is leaking so you can fix it. From all the memory profilers I've used the FlashBuilder one is still the best, the IntelliJ one was not reliable a year and Adobe Scout only does performance analysis.
Start by your smallest modules and with the memory profiler open prove that opening and closing a module (preferably in isolation of the main rig) creates a leak. If that's the case I would start by removing ALL the code from the module, and testing it again, add part by part which will lead you to the lead eventually. You can use a best suspects search, where you first address event listeners, etc.
This article from Thomas Sugden is still the best I've read about flex memory profiling and you should read it from end to end if you haven't.
It worth your time to write tools that allow you to test your modules, who knows even automate the process that evaluates if there are leaks or not. This is important because sometimes there are leaks that will not be your fault, the Flex framework has a bunch of them that you just can't avoid.
Hope this helped.
You might want to try a different container. I've personally had performance issues with VBox. And as the pervious user said, Flex has a habit of waiting until memory reaches high levels before it performs a memory sweep.
Flash doesn't always initiate the memory sweeping method, but it only frees null pointers when you are taking up memory excessively, so do mind that hindrance.

why game is running slow in libgdx?

I am making racing game in Libgdx.My game apk size is 9.92 mb and I am using four texture packer of total size is 9.92 Mb. My game is running on desktop but its run on android device very slow. What is reason behind it?
There are few loopholes which we neglect while programming.
Desktop processors are way more powerful so the game may run smoothly on Desktop but may slow on mobile Device.
Here are some key notes which you should follow for optimum game flow:
No I/O operations in render method.
Avoid creating Objects in Render Method.
Objects must be reused (for instance if your game have 1000 platforms but on current screen you can display only 3, than instead of making 1000 objects make 5 or 6 and reuse them). You can use Pool class provided by LibGdx for object pooling.
Try to load only those assets which are necessary to show on current screen.
Try to check your logcat if the Garbage collector is called. If so than try to use finalize method of object class to find which class object are collected as garbage and try to improve on it.
Good luck.
I've got some additional tips for improving performance:
Try to minimize texture bindings (or generally bindings when you're making a 3D game for example) in you render loop. Use texture atlases and try to use one texture after binding as often as possible, before binding another texture unit.
Don't display things that are not in the frustum/viewport. Calculate first if the drawn object can even be seen by the active camera or not. If it's not seen, just don't load it onto your GPU when rendering!
Don't use spritebatch.begin() or spritebatch.end() too often in the render loop, because every time you begin/end it, it's flushed and loaded onto the GPU for rendering its stuff.
Do NOT load assets while rendering, except you're doing it once in another thread.
The latest versions of libgdx also provide a GLProfiler where you can measure how many draw calls, texture bindings, vertices, etc. you have per frame. I'd strongly recommend this since there always can be situations where you would not expect an overhead of memory/computational usage.
Use libgdx Poolable (interface) objects and Pool for pooling objects and minimizing the time for object creation, since the creation of objects might cause tiny but noticable stutterings in your game-render loop
By the way, without any additional information, no one's going to give you a good or precise answer. If you think it's not worth it to write enough text or information for your question, why should it be worth it to answer it?
To really understand why your game is running slow you need to profile your application.
There are free tools avaiable for this.
On Desktop you can use VisualVM.
On Android you can use Android Monitor.
With profiling you will find excatly which methods are taking up the most time.
A likely cause of slowdowns is texture binding. Do you switch between different pages of packed textures often? Try to draw everything from one page before switching to another page.
The answer is likely a little more that just "Computer fast; phone slow". Rather, it's important to note that your computer Java VM is likely Oracles very nicely optimized JVM while your phone's Java VM is likely Dalvik, which, to say nothing else of its performance, does not have the same optimizations for object creation and management.
As others have said, libGDX provides a Pool class for just this reason. Take a look here: https://github.com/libgdx/libgdx/wiki/Memory-management
One very important thing in LibGDX is that you should make sure that sometimes loading assets from the memory cannot go in the render() method. Make sure that you are loading the assets in the right times and they are not coming in the render method.
Another very important thing is that try to calculate your math and make it independent of the render in the sense that your next frame should not wait for calculations to happen...!
These are the major 2 things i encountered when I was making the Snake game Tutorial.
Thanks,
Abhijeet.
One thing I have found, is that drawing is laggy. This means that if you are drawing offscreen items, then it uses a lot of useless resources. If you just check if they are onscreen before drawing, then your performance improves by a lot surprisingly.
Points to ponder (From personal experience)
DO NOT keep calling a function,in render method, that updates something like time,score on HUD (Make these updates only when required eg when score increases ONLY then update score etc)
Make calls IF specific (Make updations on certain condition, not all the time)
eg. Calling/updating in render method at 60FPS - means you update time 60 times a sec when it just needs to be updated once per sec )
These points will effect hugely on performance (thumbs up)
You need to check the your Image size of the game.If your image size are more than decrease the size of images by using the following link "http://tinypng.org/".
It will be help you.

AS3 Memory management when instantiating extended classes

I'm developing an AS3 application which has some memory leaks I can't find, so I'd like to ask some newbie questions about memory management.
Imagine I have a class named BaseClass, and some classes that extend this one, such as ClassA, ClassB, etc.
I declare a variable:
myBaseClass:BaseClass = new ClassA();
After a while, I use it to instantiate a new object:
myBaseClass = new ClassB();
some time after
myBaseClass = new ClassC();
and the same thing keeps happening every x millis, triggered by a timer.
Is there any memory problem here? Are the unused instances correctly deleted by the garbage collector?
Thanks!
Assuming you have no other references to the instance (or, possibly, its contents), the garbage collector will clean them up. However, the time before cleanup is, as far as I know, indeterminate (there might be some hard timeline in use, but I've never seen it documented). If you're creating a huge number of instances, you might use up a lot of memory before the first ever gets cleaned up.
There is an AS call (the name of which escapes me at the moment) to force a GC run, but it shouldn't normally be necessary. If you find it necessary, you almost certainly need to rethink how your application works.
If myBaseClass is the only stored reference to
new ClassA()
and you assign something else to myBaseClass
new ClassB()
then there will be no reference pointing to ClassA and the garbage collector should find it when it runs.
However, if you give myBaseClass to a library or class that stores its own reference to that object, when you reassign myBaseClass there will still be a reference pointing to the ClassA and the garbage collector will not clean it up, creating a memory leak. Normally a well written library will provide you with a way to remove the reference. e.g.
var child:Sprite = new Sprite()
// one reference to the new Sprite
stage.addChild(child); // assume stage stores reference
// two references to the new Sprite
/**
* assume the following:
*
* child = null;
*
* one reference would still remain in stage
* garbage collector will not clean up the sprite
*/
stage.removeChild(child); // assume stage clears reference
// one reference left
child = null;
// no reference to the sprite, garbage collector will clean it up
Hope this clears things up a bit. Essentially you want to keep track of how many references there are to an object, if you suspect it to be leaking memory.
I know that FlashDevelop has a profiler that is quite useful for finding these bugs. Also, you need to know that when the garbage collector runs... it will free up memory and give a saw tooth pattern to your memory profiler.
Good example code for demonstrating profiling in Actionscript 3
AS3 Memory Leak Example

How much resources does an unremoved event listener consume?

Let's say I've got an event listener function that is listening for an event that will never be called again throughout the lifespan of the program. The listening object will never need to be garbage collected.
How much memory does this use?
If it's negligible, I'd rather not remove the listener because having the removeEventListener() statement makes my code less readable.
That depends entirely on how large and complex the listener is. In many cases, the memory impact is negligible, however, the object you're holding in memory may be keeping several other objects in memory. If one of them is a streaming video or something, it may be sucking on your memory, processor, and network.
You can also set useWeakReferences to true when you first add the event listeners. This makes the link between the listener and the event dispatcher weak so that the latter doesn't hold the prior in memory if it's deleted everywhere else. More on that here.
Still, it's never a good idea to leave objects in memory that are not going to be used again and there's no reason to avoid removeEventListener(). Striving for code readability before making it work correctly is never a good idea. If you're that concerned with the way your code looks, put the removeEventListener() calls inside a method called cleanupUnusedListeners() or something. Indeed, I would say that omitting it is less readable because when you're looking for the source of your memory leak, it will be harder to find the spot where you DIDN'T put a removeEventListener(). It may not be pretty but that's just the way it is, Jack.
It's negligible, unless you have thousands of them. Check out how EventDispatcher works and take a look at it's source code.