Preventing memory leaks in react-konva - memory-leaks

The Konva library has a helpful list of performance optimizations. I am writing an application using react-konva and would like to specifically know if there is any work to be done when a component is unmounted to prevent memory leaks. Do I need to destroy() any konva elements for cleanup?

You don't need to worry about mem-leaks with react-konva. It automatically handles adding/destroying shapes.
You only need to apply the rules from the link if you:
Create nodes manually in some react lifecycle methods (you probably should not do that).
Use Konva.Tween functions manually. But in that case, just need to destroy it, as in the docs.
If you are just rendering shapes in "react-way" with render() function, you will be fine.

Related

Creating Three.js meshes in a WebWorker

I'm trying to offload as many Threejs computations as possible to a Web Worker. It seems to be relatively doable when just wanting the worker to create geometries. However, I still need to create a significant amount of meshes, which implies a hefty cycle on the main thread.
Is it possible to offload mesh creation to a web worker and just have the main thread add it to the scene (when ready)?
The idea would be to have the worker create an array of meshes, based on some data, and have it send it over to the main thread.
Many thanks
I am currently willing to tackle this problem in one of my projects. If you haven't started yet yours, I would suggest to have a look at https://github.com/kripken/webgl-worker first. There are two examples (one simple, one a bit more complex) that could help to start with.
I will update later this answer with more details about how to integrate wegl-worker with three.js, which might require more setup than simple webgl/worker implementation.
Unfortunately, THREEJS 3D objects (classes) are to "heavy" to be used in workers (object can't pass through "worker thread"-"main thread" boundary, even after I patched threejs lib to be used inside worker).
But I successfully use workers to load pretty large objects asynchronously.
I use Catiline.js for convenience.
The idea is to use THREEJS objects native format (and buffer geometry) and simply parse it to js object inside worker. After it, you can use THREE.ObjectLoader in the main thread to get real scene object. The benefit from such approach is to move parsing (which can take quite a long time for the large object) to background and minify freezing.
I use 6 workers, choose worker randomly, pass data url to it and additionaly get benefits from XMLHttpRequest caching
Threejs objects can't be passed through a postMessage.
Instead we want to set up a connection back to the main page via web-sockets. This should let us freely pass whatever is needed.
This thread might be helpful to you... I recently had to do some SSR with Three.js and the concepts are similar expect you are parsing Buffer Geometries with ObjectLoader in the worker.
https://discourse.threejs.org/t/error-with-ssr-three-js-objects/8643

Bindings and memory leaks

Problem
Example use case:
I have a control which displays a status gauge. The visual status of the gauge is bound to a property of the control
The control is part of a topology graph. So depending on the topology e. g. a 100 of these controls may be displayed at once
There are several topologies. Every time you switch to another topology view the whole graph is regenerated
Question
Could this cause a memory leak and do you have to perform a manual unbind in the old topology view before you create the new one? Similar to the bindings, do you have to remove event handlers manually?
The bindings and the event handlers are inside the control. So once the control isn't accessible anymore it should be possible that it's garbage collected. So I think you don't have to do anything, but I don't know.
Thank you very much for the expertise!
If you look into the JavaDocs:
[...] All bindings in our implementation use instances of WeakInvalidationListener, which means usually a binding does not need to be disposed. But if you plan to use your application in environments that do not support WeakReferences you have to dispose unused Bindings to avoid memory leaks.
So if you use or extend the default Bindings the Garbage Collector should be able to do its work.
If you do not, be sure do implement and call Binding.dispose().
As always: If an object is no longer referenced by any other object it gets garbage collected (at some point in the future). So usually one does not need to specifically implement in this direction, as it tends to clutter the code.

Are there greenDAO thread safety best practices?

I'm having a go with greenDAO and so far it's going pretty well. One thing that doesn't seem to be covered by the docs or website (or anywhere :( ) is how it handles thread safety.
I know the basics mentioned elsewhere, like "use a single dao session" (general practice for Android + SQLite), and I understand the Java memory model quite well. The library internals even appear threadsafe, or at least built with that intention. But nothing I've seen covers this:
greenDAO caches entities by default. This is excellent for a completely single-threaded program - transparent and a massive performance boost for most uses. But if I e.g. loadAll() and then modify one of the elements, I'm modifying the same object globally across my app. If I'm using it on the main thread (e.g. for display), and updating the DB on a background thread (as is right and proper), there are obvious threading problems unless extra care is taken.
Does greenDAO do anything "under the hood" to protect against common application-level threading problems? For example, modifying a cached entity in the UI thread while saving it in a background thread (better hope they don't interleave! especially when modifying a list!)? Are there any "best practices" to protect against them, beyond general thread safety concerns (i.e. something that greenDAO expects and works well with)? Or is the whole cache fatally flawed from a multithreaded-application safety standpoint?
I've no experience with greenDAO but the documentation here:
http://greendao-orm.com/documentation/queries/
Says:
If you use queries in multiple threads, you must call forCurrentThread() on the query to get a Query instance for the current thread. Starting with greenDAO 1.3, object instances of Query are bound to their owning thread that build the query. This lets you safely set parameters on the Query object while other threads cannot interfere. If other threads try to set parameters on the query or execute the query bound to another thread, an exception will be thrown. Like this, you don’t need a synchronized statement. In fact you should avoid locking because this may lead to deadlocks if concurrent transactions use the same Query object.
To avoid those potential deadlocks completely, greenDAO 1.3 introduced the method forCurrentThread(). This will return a thread-local instance of the Query, which is safe to use in the current thread. Every time, forCurrentThread() is called, the parameters are set to the initial parameters at the time the query was built using its builder.
While so far as I can see the documentation doesn't explicitly say anything about multi threading other than this this seems pretty clear that it is handled. This is talking about multiple threads using the same Query object, so clearly multiple threads can access the same database. Certainly it's normal for databases and DAO to handle concurrent access and there are a lot of proven techniques for working with caches in this situation.
By default GreenDAO caches and returns cached entity instances to improve performance. To prevent this behaviour, you need to call:
daoSession.clear()
to clear all cached instances. Alternatively you can call:
objectDao.detachAll()
to clear cached instances only for the specific DAO object.
You will need to call these methods every time you want to clear the cached instances, so if you want to disable all caching, I recommend calling them in your Session or DAO accessor methods.
Documentation:
http://greenrobot.org/greendao/documentation/sessions/#Clear_the_identity_scope
Discussion: https://github.com/greenrobot/greenDAO/issues/776

Draw on top of suspended full-screen Direct3D app

Currently, I am able to hook onto Direct3D application and draw custom stuff onto its surface. However, I would like to suspend this application and then draw something else.
Is this even remotely possible to do so? Like creating another my own Direct3D window on top of that application?
I'm targetting only Windows 7, but the application I want to draw on is using only DirectX 9.
The problem is that I have very little experience with DirectX in general.
Sort of.
You're working with two different elements here, one quite large and but not particularly complex: hooking D3D. The other ("suspending" the app) is simple within that, but you don't quite want what you think you want.
To hook D3D, by the simplest method, you need to intercept the call to CreateDirect3D9 and return your own IDirect3D9, which later creates and returns your own IDirect3DDevice9. This will give you full control over the app's render process.
In order to "suspend" it, you need to wait for the desired trigger, then in your IDirect3DDevice9::Present, call your own event loop. This will, for all intents and purposes, suspend execution of the original app's code, but not the process itself (allowing your code and event loop to process). There will be some limitations of this, and you may not be able to consume window/Windows events (simply), but it will give you full control and effectively pause the original app.
Note, however, that you must intercept and reroute execution in every thread you want to "suspend," it's only specific to a single thread and you don't want physics or AI crunching on while render and UI are paused.
You need to perform your overlay drawing, whatever that may be, during your loop or your IDirect3DDevice9::Present hook, then call the real device's Present method as needed. If you want to run multiple frames of your overlay, then call the real Present repeatedly before returning from your Present. Tweak as necessary. Rendering here is done pretty much normally (check out general D3D tutorials for that), but there is one major catch: the device's state is unknown and may be incompatible, but must be "untouched" on return. This is handled simply by caching an IDirect3DStateBlock9 created from the device immediately after creating it. In your Present hook, create another state block with the state on entrance, restore the clean state block, run your code, then restore the entrance state block. You can work with any states, off a fresh slate, without damaging the device's state (I use this in practice, in works great).
If you want some rather extensive examples of how this works, I'd suggest checking out the Voodoo Shader project, which has full D3D8 and 9 hooks, including everything needed for overlays [/shameless own-project promotion]. Feel free to reuse any of the concepts, or comment with further questions; this certainly isn't all the details that may be useful to you.
This is a very complex thing to accomplish, as it is very much a hack to do so. The only people you see doing such things are steam, teamspeak, xfire, fraps, and a few hard-core devs.
There are kits out on the internet that show you have to inject a DLL into the memory space of the target application to achieve such a feat, and methods such as proxy DLLs.
Proxy DLL:
http://www.codeguru.com/cpp/g-m/directx/directx8/article.php/c11453
Injection:
http://www.progamercity.net/d3d/372-c-directx9-0-hooking-via-detours.html
Good luck, this will take you a while.

Can anyone point me to some strategies for debugging memory leaks in monotouch?

I am almost finished with my first monotouch app, almost that is, but for some big problems with memory leaks. Even though I override the viewDidUnload on every view controller so that for every UI element that I create I first remove it from its superview, then call Dispose and then set it to null, the problem persists. Using Instruments is no help, it doesn't detect the memory leaks and the memory allocations doesn't point me to anything that I can track.
My app uses mainly the MPMoviePlayer to play video streams and also displays an image gallery from images loaded through http. Both operation are causing problems.
Any ideas would be very much appreciated, thanks.
The Master is right of course. Gracias Miguel. I wanted though to give a more thorough explanation of what I did, with the hope that it may help future Xamarin colleges.
1) The MPMoviePlayer stores a video buffer which is kind of sticky. What I have done is have a unique instance running on the AppDelegate an reuse this across the views that show a video. So instead of initializing the MPMoviePlayerController with an url you use the constructor with no arguments, and then set the ContentUrl property and call Play().
2) Do not rely on ViewDidUnload being called to clean up you objects, because it is not called consistently. For example I use a lot of modal view controllers and this method never got called. Memory just kept accumulating until the app crashed. Better call you clean up code directly.
3) Images were the biggest memory hug I had. Even Images inside UIImageViews that were just used as background would never get disposed. I had to specifically call the following code on each image before I could clear up the memory:
myImageView.RemoveFromSuperview();
myImageView.Image.Dispose();
myImageView.Image = null;
myImageView.Dispose();
myImageView = null;
4) Beware of the UIWebView, it can hug a lot of memory, specially if there is some kind of AJAX interaction running on the page that you are loading. Calling the following code help a little but didn't solve all the problems. Some memory leaks remain that I wasn't able to get rid off:
NSString keyStr = new NSString("WebKitCacheModelPreferenceKey");
NSUserDefaults.StandardUserDefaults.SetValueForKey(NSObject.FromObject(val), keyStr);
5) If you can, avoid using Interface Builder. On several occasions I was never able to release UI elements created on the xib files. Positioning everything by hand can be a pain but if you are using a memory intensive application creating all your view controllers in code may be the way to go.
6) Using anonymous methods as event handlers is nice and my help code readability, but on some occasions not being able to manually detach an event handler became a problem. References to unwanted object remain in memory.
7) In my UITableViewSource I was able to have a more efficient memory handling by creating the UIImages that I use to style the cells independently and then just reusing them on my GetViewForHeader and GetCell methods.
One last thing; even though instruments is not really compatible with the way monotouch is doing things using the "Memory Monitor" was a valuable tool, if you are having problem it can indeed help.
These strategies solved most of my problems. Some may be pretty obvious in hindsight but I thought it wont hurt to pass them along.
Happy Coding and long live c# on the iPhone
The UI elements are not likely the responsible ones, those barely use any memory. And calling Dispose()/nulling helps, but only a tiny bit.
The more likely source of the problem are objects like the MPMoviePlayer, the image downloading and the image rendering. You might be keeping references to those objects which prevent the GC from getting rid of them.

Resources