Using a global array instead of a local one, any performance difference?

Take this code for example: https://play.crystal-lang.org/#/r/75ou

SuffixArray = ["i_atk_speed", "gfiuorhng", "ierojt", "20 more mods listed here in this array"]
PrefixArray = ["i_phys", "gfiuorhng", "ierojt", "20 more mods listed here in this array"]

GlobalModArray = SuffixArray + PrefixArray


def roll_mods()
  mods_to_roll = SuffixArray + PrefixArray
  pp mods_to_roll
end


roll_mods

Is there any performance difference between mods_to_roll (creating a new local variable each time roll_mods is called), and GlobalModArray?

Using GlobalModArray inside roll_mods is the correct way to do this, right? Unless I need mods_to_roll to be mutable, correct?

If I use GlobalModArray, I won’t have have to create a local variable and append both arrays. Since that was already done when the app started, that array is now in memory. Thus, it’s faster to access?

GlobalArray, like any constant, is computed once. If you use a local variable it will be computed each time you call that method. So using GlobalArray is definitely faster.

1 Like

Good to know!! I like that, and just thought of that when creating my method.

Especially when the Suffix and Prefix lists will become very large. I can just compute them once when the app starts and select a random key based on their list size, instead of shuffling all of them all the time!

Also, I think you should use tuple instead of array.

Tuples are handled at compile time.