What is pre-hashing?
To make the development easily readable, we give objects a descriptive 'Id' property. This is a string that is easy for humans to recognise such as, 'player'. However, to maximise performance, internally Defold is storing the object with an identifier that is an integer. A hashing algorithm is used to convert the string that is useful for humans into an integer that is useful for a computer.
A hashing algorithm takes a set of alphnumeric characters and applies a mathematical formula to them to derive a number. A simple way of achieving this would be to convert each character in a string to it's ASCII value and add up all the numbers. However, this is a very simplistic approach. Defold uses the 64-bit MurmurHash2A algorithm, modified to be endian-neutral.
In code, hash() is used every time we refer to an object. Since the update() or on_input() function of a script executes many times a second, it is calling this hashing algorithm many, many times, achieving the same output every time! To further maximise performance we could calculate the output of the hashing algorithm just once and store this in a variable instead. This is known as pre-hashing. In conditions in the code we then compare the variable rather than the hash of a string. It increases the memory footprint slightly while increasing the performance significantly.
An example without pre-hashing:
function on_input(self, action_id, action)
if action_id == hash("left") then
self.direction.x = -1
elseif action_id == hash("right") then
self.direction.x = 1
end
end
An example with pre-hashing:
local move_left = hash("left")
local move_right = hash("right")
function on_input(self, action_id, action)
if action_id == move_left then
self.direction.x = -1
elseif action_id == move_right then
self.direction.x = 1
end
end