Typeof() vs explicit types for Native Code performance

Hi, I’m working on a performance-critical system where every millisecond in the loop counts, and I’m using --!native for optimization.

I’ve been using typeof() to define my complex data types to avoid repeating code (writing interface and then default values for example)

But I’ve heard some talk that this might actually affect native code performance. The idea was that since the type isn’t “strictly” static, the compiler might spend more time trying to figure out the shape of the object or generate more runtime guards compared to a manual type/interface declaration.

Does anyone know if the Native Code Generator treats these two differently? Does using typeof() lead to slower machine code or more de-optimizations in the long run? I’m mostly worried about the execution speed, not the Studio linter speed.

1 Like

Slow as opposed to what? Not using typeof? It’s really hard to tell without seeing your use case; typeof doesn’t cost anything within types, and also can be optimized away during compile time given the inner expression has an unconditional type.

Hello. There actual example of what I mean.

-- Static
export type StaticState = {
	Position: Vector3,
	Velocity: Vector3,
}

local STATIC_STATE_DEFAULT: StaticState = {
	Position = Vector3.zero,
	Velocity = Vector3.zero,
}

local function StaticStateFactory(overrides: { [any]: any }?): StaticState
	return Utility.Table.Merge(STATIC_STATE_DEFAULT, overrides)
end

StaticStateFactory({ Position = Vector3.new(0, 5, 0) })

-- Dynamic
local DYNAMIC_STATE = {
	Position = Vector3.zero,
	Velocity = Vector3.zero,
}

export type DynamicState = typeof(DYNAMIC_STATE)

local function DynamicStateFactory(overrides: { [any]: any }?): DynamicState
	return Utility.Table.Merge(DYNAMIC_STATE, overrides)
end

DynamicStateFactory({ Position = Vector3.new(0, 5, 0) })

Actually only INTERFACE of State is referenced each frame.
I just wondered what better for system where each millisecond of perfomance matters.

Does this hurts Native mode perfomance? Or “typeof” defines type only one time in the runtime, and works as fast as statically defined does further?

In this case typeof would have absolutely zero effect, you’re using it in type context which is purely compile time anyway.

1 Like

Alright, thanks you. Just got tired of manually writing interface even when I have mandatory defaults for each one.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.