Check if an object has changed

前端 未结 5 2216
闹比i
闹比i 2021-02-19 21:31

Is there a more native way (e.x. a built-in function) with less userland code to check if an objects property values have changed instead of using one of those methods:

5条回答
  •  北海茫月
    2021-02-19 22:23

    While I too am looking for a very fast/faster approach, a variant of method 2 is effectively what I use. The advantage of this method is that it is (pretty) fast (in comparison to an isset()), depending on object size. And you don't have to remember to set a ->modified property each time you change the object.

    global $shadowcopy; // just a single copy in this simple example.
    $thiscopy = (array) $obj; // don't use clone.
    if ($thiscopy !== $shadowcopy) {
    // it has been modified
    // if you want to know if a field has been added use array_diff_key($thiscopy,$shadowcopy);
    
    }
    $shadowcopy = $thiscopy; // if you don't modify thiscopy or shadowcopy, it will be a reference, so an array copy won't be triggered.
    

    This is basically method 2, but without the clone. If your property value is another object (vobj), then clone may be necessary (otherwise both references will point to the same object), but then it is worth noting that it is that object vobj you want to see if has changed with the above code. The thing about clone is that it is constructing a second object (similar performance), but if you want to see what values changed, you don't care about the object itself, only the values. And array casting of an object is very fast (~2x the speed of a boolean cast of a bool) .. well, up until large objects. Also direct array comparison === is very fast, for arrays under say 100 vals.

    I'm pretty sure an even faster method exists...

提交回复
热议问题