Constructor: set this reference

I've an already implemented application which connects to a database. Now, the problem is that I need to implement a caching system (if easily possible) for some of the objects because their initialization takes too long for getting the needed data from the database every time when I need those objects. (Those objects won't change quite often and in fact, I could update them using a timestamp if necessary.)

Since I can't easily change the whole application I'd like to know if there is any method so that I can set the "this" object within the constructor itself. I am referring to the ability of Objective-C where I am able to call any method that returns an id and set it to the self "variable" which then updates in fact the whole object. To explain my idea a bit better: I want to initialize a static cache in those classes and get the already stored object (if available) within the constructor. Please note that all setters refer to SQL code too.

I also know that I could just use the getters of the already stored object to set the values of the new one within the constructor but this would create many objects too and in case there might be a change in the values I won't replicate this to all other objects cloned from that one.

Any ideas, thanks?!

Upvotes: 0

Views: 102

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533492

A constructor only operates on a new object. If you want to reuse objects, you cannot use the constructor. Creating the object itself is trivial << 100 ns which leads me to believe you don't need to recycle the object, but the data in the object which comes from the database.

Accessing a database is about 0.1 to 10 ms. Creating an object is 10 to 100 ns (on millionth of a milli-second) If you are concerned about the cost of creating new objects, you shouldn't be using a database at all as it could one million time more expensive.

Upvotes: 4

Related Questions