Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A rule for converting math.sqrt(x) #223

Open
jiwonz opened this issue Oct 29, 2024 · 1 comment
Open

A rule for converting math.sqrt(x) #223

jiwonz opened this issue Oct 29, 2024 · 1 comment

Comments

@jiwonz
Copy link
Contributor

jiwonz commented Oct 29, 2024

In Luau, the difference is smaller than in Lua 5.3 maybe due to fastcall, but there is still a function call overhead, so converting math.sqrt(x) to (x)^.5 may be helpful for (micro) optimization. (I actually did some benchmarking.)

Benchmarking code

-- math.sqrt(x)
start = os.clock() for i = 1, 1e7 do local result = math.sqrt(123.456) end print(os.clock() - start)

-- (x)^.5
start = os.clock() for i = 1, 1e7 do local result = 123.456^.5 end print(os.clock() - start)

Lua 5.3

-- math.sqrt(x)
0.427 -- very slow tho I'm not sure 100% why

-- (x)^.5
0.050000000000001

Luau

-- math.sqrt(x)
0.07609090000914875

-- (x)^.5
0.027639599997201003

The edge case of conversion is that the result after converting math.sqrt(x) to (x)^.5 can be different depending on the type and version of Lua. I have tested in advance that 1:1 conversion works well in both Lua 5.3 and Luau.

A rule name could be convert_sqrt or convert_math_sqrt.

@ewd3v
Copy link

ewd3v commented Nov 7, 2024

This would also mean some numbers could take advantage of compute_expression.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants