Why is using built-in variables faster than custom variables?

Discuss Autohotkey related topics here. Not a place to share code.
Forum rules
Discuss Autohotkey related topics here. Not a place to share code.
william_ahk
Posts: 700
Joined: 03 Dec 2018, 20:02

Why is using built-in variables faster than custom variables?

Post by william_ahk » 24 Nov 2024, 23:43

One would think that it would be slower for built-in variables to dynamically resolve than storing the reference to a custom variable. But my tests below seem to show that that is not the case. Can someone explain the how behind it?

Code: Select all

#Requires AutoHotkey v2.0
#SingleInstance Force
ListLines 0

; Globals
Tray := A_TrayMenu

; Cases
TestCases := [
	() => (A_TrayMenu),
	() => (Tray),
]
; Test
TestCount := 10000000
TimeRecords := []
BestRecord := 9223372036854775807 ; LLONG_MAX
For Index, TestCase in TestCases {
	QPC(1)
	Loop TestCount
		TestCase()
	Record := QPC()
	If Record < BestRecord
		BestRecord := Record
	TimeRecords.Push(Record)
}

Result := ""
For Record in TimeRecords {
	Result .= Record (Record = BestRecord ? " <-" : "") "`n"
}
Msgbox Result
My results:
4.6398664 <-
4.6715327

lexikos
Posts: 9811
Joined: 30 Sep 2013, 04:07
Contact:

Re: Why is using built-in variables faster than custom variables?

Post by lexikos » 15 Dec 2024, 22:18

Why do you think that built-in variables would "dynamically resolve" while custom variables would have a reference stored?

They are both resolved to addresses at load time, and although the type of indirection differs, it is not in any significant way.

Only a fraction of the time needed for each iteration of your benchmark is actually used to evaluate the variable reference. It is such an insignificant operation that coincidental factors such as the layout of your script (or AutoHotkey's binary code) in memory can have a greater effect on the performance (e.g. due to CPU cache and other low-level CPU optimizations).

Post Reply

Return to “General Discussion”