darklua icon indicating copy to clipboard operation
darklua copied to clipboard

A rule for converting `math.sqrt(x)`

Open jiwonz opened this issue 1 year ago • 1 comments

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.

jiwonz avatar Oct 29 '24 07:10 jiwonz

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

ewd3v avatar Nov 07 '24 11:11 ewd3v