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

Optimize ents.FindByClassAndParent #2167

Open
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

Astralcircle
Copy link
Contributor

@Astralcircle Astralcircle commented Dec 2, 2024

Optimizes this function by about 25%

Benchmark code:

local SysTime = SysTime
local ipairs = ipairs
local MsgN = MsgN

function GMODBenchmark(repeats, ...)
    local times = {}

    for k, benchmark_function in ipairs({...}) do
        local start_time = SysTime()

        for i = 1, repeats do
            benchmark_function()
        end

        local end_time = SysTime()
        times[k] = end_time - start_time
    end

    MsgN(string.format("\nBenchmark result %s:", SERVER and "(SERVER)" or "(CLIENT)"))
    for k, v in ipairs(times) do
        MsgN(k, ": " .. v)
    end
end

Benchmark:

function ents.FindByClassAndParent2( classname, entity )

    local entslist = ents.FindByClass( classname )
	local out = {}

    for k, v in ipairs( entslist ) do

        local p = v:GetParent()
		if ( !IsValid(p) ) then continue end
		if ( p != entity ) then continue end

		table.insert( out, v )

    end

	if ( out[1] == nil ) then return end

	return out

end

local e = Entity(1)

--155 props parented to player
GMODBenchmark(10000, 
function()
    local a = ents.FindByClassAndParent2("prop_physics", e)
end,
function()
    local a = ents.FindByClassAndParent("prop_physics", e)
end)

Result:

Benchmark result (SERVER):
1: 0.26664929999993
2: 0.35286960000008

@aStonedPenguin
Copy link
Contributor

Just use ipairs. With jit it should be the same speed, and cleaner.

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

Successfully merging this pull request may close these issues.

2 participants