c# - How do I implement caching in an immutable way? -
i've read , heard lot of things immutability, decided try out in 1 of hobby projects. declared of fields readonly, , made methods mutate object return new, modified version.
it worked great until ran situation method should, external protocol, return information object without modifying it, @ same time optimized modifying internal structure. in particular, happens tree path compression in union find algorithm.
when user calls int find(int n)
, object appears unmodified outsider. represents same entity conceptually, it's internal fields mutated optimize running time.
how can implement in immutable way?
short answer: have ensure thread-safety yourself.
the readonly
keyword on field gives insurance field cannot modified after object containing field has been constructed. write can have field contained in constructor (or in field initialization), , read through method call cannot occur before object constructed, hence thread-safety of readonly
.
if want implement caching, break assumption 1 write occurs (since "caching writes" can , occur during reads), , there can threading problems in bad cases (think you're reading lines file, 2 threads can call find method same parameter read 2 different lines , therefore different results). want implement observational immutability. related question memoization may elegant answer.
Comments
Post a Comment