Skip to content

Commit 78dd590

Browse files
committed
Override __deepcopy__ to improve performance.
1 parent 8a3e825 commit 78dd590

2 files changed

Lines changed: 20 additions & 9 deletions

File tree

pygenalgo/genome/chromosome.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -218,10 +218,16 @@ def __deepcopy__(self, memo):
218218
memo[id(self._cache)] = self._cache.__new__(dict)
219219
# _end_if_
220220

221-
# Deep copy all other attributes.
222-
for key, value in self.__dict__.items():
223-
setattr(new_object, key, deepcopy(value, memo))
224-
# _end_for_
221+
# Deepcopy ONLY the genome because
222+
# it is a (mutable) list of Genes.
223+
setattr(new_object, "_genome",
224+
deepcopy(self._genome, memo))
225+
226+
# Simply copy the fitness value.
227+
setattr(new_object, "_fitness", self._fitness)
228+
229+
# Simply copy the boolean flag.
230+
setattr(new_object, "_valid", self._valid)
225231

226232
# Return identical instance.
227233
return new_object

pygenalgo/genome/gene.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -213,11 +213,16 @@ def __deepcopy__(self, memo):
213213
memo[id(self._cache)] = self._cache.__new__(dict)
214214
# _end_if_
215215

216-
# Deep copy all other attributes.
217-
for attr in self.__slots__:
218-
setattr(new_object, attr,
219-
deepcopy(getattr(self, attr), memo))
220-
# _end_for_
216+
# Deepcopy ONLY the datum because it
217+
# might be a complex mutable object.
218+
setattr(new_object, "_datum",
219+
deepcopy(self._datum, memo))
220+
221+
# Simply copy the function handle.
222+
setattr(new_object, "_func", self._func)
223+
224+
# Simply copy the boolean flag.
225+
setattr(new_object, "_valid", self._valid)
221226

222227
# Return identical instance.
223228
return new_object

0 commit comments

Comments
 (0)