· Dec 15, 2023

How to clone dynamic objects?

How to clone dynamic objects more efficiently than using a serialization/desserialization approach (eg. Set objectB = {}.%FromJSON(objectA.%ToJSON()) ) ?

Why %DynamicObject could not extend %RegisteredObject and its %ConstructClone method (if not inherit it)?

Discussion (4)3
Log in or sign up to continue

A few lines of code and you have your own object cloner

Class DC.ObjCloner [ Abstract ]
/// obj: Cache/IRIS or a Dynamic(JSON) Object
/// For simplicity, JSON-Types null, true, false, etc. are ignored
ClassMethod Clone(obj)
    if $isobject(obj) {
        if obj.%IsA("%DynamicAbstractObject") {
            if obj.%IsA("%DynamicObject") { set new={},arr=0 } else { set new=[], arr=1 }
            set iter=obj.%GetIterator()
            while iter.%GetNext(.key,.val) {
                set:$isobject(val) val=..Clone(val)
                do $case(arr, 1:new.%Push(val), :new.%Set(key,val))
            quit new
        } else { quit obj.%ConstructClone(1) }
    } else { quit "" }

@Julius Kavay , nice code.

But the point was "more efficiently than using a serialization/deserialization", with this code it takes more than 4 times as serialization/deserialization.

I think that using serialization/deserialization IS very efficient.

@Rodrigo Werneck , are you having performance issues? What makes you think serialization/deserialization is inefficient? Did you measure the performance in your use case?