Skip to content

Commit

Permalink
Optimize Dex#getEffect by caching the result.
Browse files Browse the repository at this point in the history
As outlined by pkmn.cc/optimize, this change should result in a ~30%
increase in Battle performance over repeated runs. Caching the
resultant effect is safe provided nothing mutates it.
  • Loading branch information
scheibo committed Feb 20, 2019
1 parent a13da24 commit 31c6a32
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions sim/dex.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,8 @@ class ModdedDex {
this.abilityCache = new Map();
/** @type {Map<string, TypeInfo>} */
this.typeCache = new Map();
/** @type {Map<string, PureEffect>} */
this.effectCache = new Map();

if (!isOriginal) {
const original = dexes['base'].mod(mod).includeData();
Expand Down Expand Up @@ -458,10 +460,8 @@ class ModdedDex {
moveCopy.hit = 0;
return moveCopy;
}

/**
* While this function can technically return any kind of effect at
* all, that's not a feature TypeScript needs to know about.
*
* @param {?string | Effect} [name]
* @return {PureEffect}
*/
Expand All @@ -473,6 +473,22 @@ class ModdedDex {
// @ts-ignore
return name;
}

let cached = this.effectCache.get(name);
if (!cached) {
cached = this.getEffectInner(name);
this.effectCache.set(name, cached);
}
return cached;
}

/**
* While this function can technically return any kind of effect at
* all, that's not a feature TypeScript needs to know about.
* @param {string} name
* @return {PureEffect}
*/
getEffectInner(name) {
if (name.startsWith('move:')) {
// @ts-ignore
return this.getMove(name.slice(5));
Expand Down

0 comments on commit 31c6a32

Please sign in to comment.