rather than having to perform the calculation every single time we want to look up anything relating to stats, wouldn’t it make more sense to save the current level after we’ve found it? or is the look-up vs memory cost more worthwhile to not cache it?
There are two answers for this, and it depends on which way you want to go.
If ExperienceRequired is the amount of total experience you need to level up, then no, you never want to cache the level, because this is something that should always be calculated based on experience.
If ExperienceRequired is the amount of experience you need to earn for just that level (World Of Warcraft), then you should always cache the level, and reset the experience to currentExperience - experienceRequired when levelling up.
I was also wondering about this. We have some nice central points to be calculating the level on load, and when experience changes. That would save us from doing this multiple times per update. As we introduce more stats and more attributes calculating your level could easily get out of control. In the next lecture we add the Level Display, which puts us at 3 runs per update.
Curious if it makes more sense for us to calculate only when there’s a change as opposed to constantly.
One of the hardest sources of bugs to diagnose and fix is caching state. It’s difficult to diagnose because unlike errors like null reference errors, we often don’t get an actual error message when a cached state doesn’t match the actual state of an object. All we get is behavior that doesn’t match our predictions.
That’s not necessarily saying that we shouldn’t cache the level, and sometimes for performance, it’s required, but be sure that it’s done with some constraints. In this case, it is probably ok to cache it in BaseStats, but shouldn’t be cached in other components.
Thanks,
Appreciate the clarification, good things to consider.
Edit: Just a heads up Sam addresses this in the event/delegates section a few lessons ahead of here.