Java (android) reusing objects
I have an object which will be constructed from fields in an SQLite database cursor.
Methods in the object will be used to then test against an object of the same type and return a score. There will be many of these tests executed and I'd like to reuse thi开发者_开发问答s object - just re-initialising it from the database each time it's needed. I'm wanting to do this to avoid allocating an excessive amount of memory.
Is there a way to reuse the constructor to rebuild the object each time without creating a new one?
Or do I need to create a public method to populate the fields from a cursor and then call that in the constructor?
thanks, m
You can't use the constructor - that is only used when creating new objects. So you'd need to write a method, as per the end of your answer.
However, I would question whether you really need to do this - how often are you querying the database, and have you actually established that this is a performance bottleneck? It may be (I'm aware of the constraints of mobile development) but it will also make the code less elegant and could easily lead to subtle bugs... at the very least, you should measure performance before and after the change to see what the improvement is.
精彩评论