Skip to content

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

@jiwonz

Description

@jiwonz

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions