Add caching of `cirq.to_json(frozen_circuit)`
Is your feature request related to a use case or problem? Please describe.
Serializing large circuits can be expensive and it would be nice to cache the result for immutable objects like FrozenCricuit.
Describe the solution you'd like
Add a cached _json_string_ method to the serialization protocol. Something like
def _json_dict_(self): # existing method
attribute_names = ['moments', 'tags'] if self.tags else ['moments']
ret = protocols.obj_to_dict_helper(self, attribute_names)
return ret
@_compat.cached_method
def _json_string_(self):
return cirq.to_json(self)
and then check in to_json if _json_string_ exists and use it if it does
Open to other solutions, though!
What is the urgency from your perspective for this issue? Is it blocking important work?
P1 - I need this no later than the next release (end of quarter)
Why not add the cached_method decorator on _json_dict_ directly? Are you worried that the return value is not immutable?
Why not add the
cached_methoddecorator on_json_dict_directly? Are you worried that the return value is not immutable?
Yeah this was my first thought as well and I tried it, however it didn't make any difference. I think that is because _json_dict_ just returns a dict representation of the class and we still need to go in and recursively call to_json on everything inside the dict, which is what takes time. But it's possible I got that wrong.
@andbe91 To confirm, you do have a use case where you'd serialize the same FrozenCircuit repeatedly? Is this the case where a frozen circuit is wrapped in a circuit operation?
@andbe91 To confirm, you do have a use case where you'd serialize the same
FrozenCircuitrepeatedly?
That is correct.
Is this the case where a frozen circuit is wrapped in a circuit operation?
No, but in some internal code we pass around the same circuit to a few different classes that all need to be serialized, so we end up serializing the same circuit multiple times.