Skip to content

Commit 38c385a

Browse files
authored
Optimize lookup functions by caching array accesses (#296)
Reduced redundant array accesses in tableValue, lookupTable, and lookupArray functions. Each iteration now caches the lookup result in a local variable instead of accessing the same array element twice (once for keyHash and once for key). This reduces array subscript overhead in hot paths during table and key lookups, particularly beneficial for documents with many nested tables.
1 parent 1dbaad6 commit 38c385a

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

Sources/TOMLDecoder/Parsing/Parser.swift

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1840,19 +1840,22 @@ extension Parser {
18401840
func tableValue(tableIndex: Int, keyed: Bool, key: String, keyHash: Int) -> InternalTOMLTable.Value? {
18411841
let table = keyed ? keyTables[tableIndex].table : tables[tableIndex]
18421842
for kv in table.keyValues {
1843-
if keyValues[kv].keyHash == keyHash, keyValues[kv].key == key {
1843+
let kvPair = keyValues[kv]
1844+
if kvPair.keyHash == keyHash, kvPair.key == key {
18441845
return .keyValue(kv)
18451846
}
18461847
}
18471848

18481849
for arr in table.arrays {
1849-
if keyArrays[arr].keyHash == keyHash, keyArrays[arr].key == key {
1850+
let arrPair = keyArrays[arr]
1851+
if arrPair.keyHash == keyHash, arrPair.key == key {
18501852
return .array(arr)
18511853
}
18521854
}
18531855

18541856
for table in table.tables {
1855-
if keyTables[table].keyHash == keyHash, keyTables[table].key == key {
1857+
let tablePair = keyTables[table]
1858+
if tablePair.keyHash == keyHash, tablePair.key == key {
18561859
return .table(table)
18571860
}
18581861
}
@@ -1864,7 +1867,8 @@ extension Parser {
18641867
let table = keyed ? keyTables[tableIndex].table : tables[tableIndex]
18651868
for i in 0 ..< table.tables.count {
18661869
let tableIndexAtPosition = table.tables[i]
1867-
if keyTables[tableIndexAtPosition].keyHash == keyHash, keyTables[tableIndexAtPosition].key == key {
1870+
let tablePair = keyTables[tableIndexAtPosition]
1871+
if tablePair.keyHash == keyHash, tablePair.key == key {
18681872
return tableIndexAtPosition
18691873
}
18701874
}
@@ -1875,7 +1879,8 @@ extension Parser {
18751879
let table = keyed ? keyTables[tableIndex].table : tables[tableIndex]
18761880
for i in 0 ..< table.arrays.count {
18771881
let arrayIndex = table.arrays[i]
1878-
if keyArrays[arrayIndex].keyHash == keyHash, keyArrays[arrayIndex].key == key {
1882+
let arrPair = keyArrays[arrayIndex]
1883+
if arrPair.keyHash == keyHash, arrPair.key == key {
18791884
return arrayIndex
18801885
}
18811886
}

0 commit comments

Comments
 (0)