Skip to content

Commit 2eb5afb

Browse files
authored
[CMASolutionDict] reduce number of expensive key computations in insert
Merge pull request #336 from PaulStahr/development Improve performance by reducing redundant dictionary fetches.
2 parents f90bb5c + 8caaea3 commit 2eb5afb

File tree

2 files changed

+13
-14
lines changed

2 files changed

+13
-14
lines changed

cma/evolution_strategy.py

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,7 @@ def __init__(self, *args, **kwargs):
285285

286286
# TODO: insert takes 30% of the overall CPU time, mostly in def key()
287287
# with about 15% of the overall CPU time
288+
# NOTE: Likely improved by reducing calls to def key() on Jan 2026 (PR #336).
288289
def insert(self, key, geno=None, iteration=None, fitness=None,
289290
value=None, cma_norm=None):
290291
"""insert an entry with key ``key`` and value
@@ -308,29 +309,26 @@ def insert(self, key, geno=None, iteration=None, fitness=None,
308309

309310
self.last_solution_index += 1
310311
if value is not None:
311-
try:
312-
iteration = value['iteration']
313-
except:
314-
pass
312+
iteration = value.get('iteration', iteration)
315313
if iteration is not None:
316314
if iteration > self.last_iteration:
317315
self.last_solution_index = 0
318316
self.last_iteration = iteration
319317
else:
320318
iteration = self.last_iteration + 0.5 # a hack to get a somewhat reasonable value
321319
if value is not None:
322-
self[key] = value
320+
entry = value
323321
else:
324-
self[key] = {'pheno': key}
322+
entry = {'pheno': key}
325323
if geno is not None:
326-
self[key]['geno'] = geno
327-
if iteration is not None:
328-
self[key]['iteration'] = iteration
324+
entry['geno'] = geno
325+
entry['iteration'] = iteration
329326
if fitness is not None:
330-
self[key]['fitness'] = fitness
327+
entry['fitness'] = fitness
331328
if cma_norm is not None:
332-
self[key]['cma_norm'] = cma_norm
333-
return self[key]
329+
entry['cma_norm'] = cma_norm
330+
self[key] = entry
331+
return entry
334332

335333
class _CMASolutionDict_empty(dict):
336334
"""a hack to get most code examples running"""

cma/transformations.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1123,11 +1123,12 @@ def from_bounds(x, copy=False):
11231123

11241124
if archive is not None:
11251125
try:
1126-
x = archive[y]['geno']
1126+
archive_y = archive[y]
1127+
x = archive_y['geno']
11271128
except (KeyError, TypeError):
11281129
x = None
11291130
if x is not None:
1130-
if archive[y]['iteration'] < archive.last_iteration:
1131+
if archive_y['iteration'] < archive.last_iteration:
11311132
# no current archived genotype was found!?
11321133
x = repair_and_flag_change(self, repair, x, copy)
11331134
# x = repair(x, copy_if_changed=copy)

0 commit comments

Comments
 (0)