Not even sure how to title this or explain it but the code snippets (written in OOP design) should make it easier. I’m going to set up the example then ask my question at the end:
This is just an example, the details don’t have much to do with my question:
Say I have this function called SetCFrame() for a particular Object that is called on Heartbeat by some other script or module. For some Instances of this Object, I want the CFrame to be ‘sliding,’ while for other Instances, I want the CFrame to be ‘free moving.’ A simple way to go about this is using an if/else statement like so:
function Object:SetCFrame(cFrame)
if self.FreeOrSliding == "Free" then
self:SetCFrameFree(cFrame)
elseif self.FreeOrSliding == "Sliding" then
self:SetCFrameSliding(cFrame)
end
end
function Object:SetCFrameFree(cFrame)
-- Set the CFrame via free moving!
end
function Object:SetCFrameSliding(cFrame)
-- Set the CFrame via sliding!
end
Or something along these lines. But my problem is that SetCFrame() is being called in rapid succession and the code will have to go through this if/else statement every time unnecessarily, since the property self.FreeOrSliding is either totally fixed, or barely ever changes.
An alternative that speeds this up (I think):
function Object:SetObjectType(freeOrSliding)
if freeOrSliding == "Free" then
self.SetCFrame = self.SetCFrameFree
elseif freeOrSliding == "Sliding" then
self.SetCFrame = self.SetCFrameSliding
end
end
function Object:SetCFrameFree(cFrame)
-- Set the CFrame via free moving!
end
function Object:SetCFrameSliding(cFrame)
-- Set the CFrame via sliding!
end
The function SetObjectType() is barely ever called or only called once upon the object’s instantiation. Now SetCFrame() can be called like crazy and it won’t have to go through an if/else every time.
So my question is: Is doing my second method worth it or is it just a complete and utter useless micro-optimization. What about if there were more possibly branches, meaning the function could through a bunch of if statements before finally reaching else?
Maybe there is a third even more efficient method?