Is it good to do this?

Is this

local myCFrame = CFrame.new

faster/better than doing:

CFrame.new()

If so why?

The reason for having it as a variable is for reuse, so rsther than recalculating it again you can do it once and hold that value

1 Like

Would this improve speed by storing it as a local variable?

No, it won’t improve your script speed.

Potentially yes, it also makes scripting it easier as you can follow your code easier and quickly recall the variable.in terms of script running speed it can cut down on calculations needed if you were constantly recalculating cframes that are the same it would reduce that

1 Like

You should try benchmarking when your unsure about speed, here are my results:

-- output1

CFrame.new() took: 159ms for 1,000,000 iterations. 
Using a variable for CFrame.new() took: 148ms for 1,000,000 iterations.

-- output2
CFrame.new() took: 13550ms for 100,000,000 iterations.
Using a variable for CFrame.new() took: 14362ms for 100,000,000 iterations.

You can compare and choose yourself, note that this is in milliseconds and runs millions of time so the difference will be very negligible.

1 Like

Isn’t one suppose to say ‘using a variable for CFrame.new() and not using a varaible for CFrame.new()’? I am confused.

If you were making a load of them yes in theory the variables take longer to actually create, but its what it saves you in the actual script. This kind of one sided data is actually counter productive to think about, if you were performing complex math the time save speaks for itself

2 Likes

I don’t get what you mean. I ran the code once for one million iterations then got “output1” then repeated again with a hundred million then got “output2”.

After writing I understood what you meant so ya. It doesn’t matter what it says, that is just a print, the first one is normal CFrame.new() and the other is having a variable with the value CFrame.new and calling it.

1 Like

Either way the takeway from this, if you have to reuse the value for anything just make it a variable, if its a one time use within a calculatiom or something you dont need it as a variable

1 Like

If you look at old lua performance tips it actually did improve performance. Here is a part of a performance document from 2008:

For instance, the code
for i = 1, 1000000 do
local x = math.sin(i)
end
runs 30% slower than this one:
local sin = math.sin
for i = 1, 1000000 do
local x = sin(i)
end

Now that just isn’t true as optimizers and such have improved. Going with CFrame.new() is probably more readable if you ever share your code whereas myCFrame will get confused with being a variable of a CFrame value as oppose to it having been set to the CFrame.new function.

1 Like