Suppose I’m loading a large number of objects from a database. These are normal, plain PHP objects, no inheritance from anything fancy. Suppose I might change a few of these objects and want to write them back to the database, but only use the fields that actually differ in the UPDATE … SET … query. Also suppose that I don’t know in advance which objects are going to be changed.
I’m thinking that I need to make a copy of all the objects loaded, and keep around for reference and comparison, should I need to write objects back to the database.
I see two possible approaches:
- I can either clone all the loaded objects and store in a separate list. When saving, look up the object in the list using an index, and compare the values.
- Or, I can simply serialize everything loaded into a string, and keep around. When saving, find the serialized object in the string (somehow), unserialize it, compare the values, and there you go.
In terms of efficiency (mostly memory, but speed is also a consideration), which would be favorable?
Well you actually needs something to compare if the state of the object has changed or not. If you even want to track not only which object has changed but also which member, you need to have a state per member.
As you don’t want to extend the original objects (e.g. they could have a flag they invalidate when they are changed), you need to track the state from the outside. I’d say serializing is probably the best option then. Cloning will take more memory.