Skip to content

Commit 241efd8

Browse files
committed
improve performance of fieldname by moving out error paths in separate functions (#38921)
(cherry picked from commit 9921e8c)
1 parent 54c27e4 commit 241efd8

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

base/reflection.jl

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -143,15 +143,19 @@ julia> fieldname(Rational, 2)
143143
```
144144
"""
145145
function fieldname(t::DataType, i::Integer)
146-
if t.abstract
147-
throw(ArgumentError("type does not have definite field names"))
146+
throw_not_def_field() = throw(ArgumentError("type does not have definite field names"))
147+
function throw_field_access(t, i, n_fields)
148+
field_label = n_fields == 1 ? "field" : "fields"
149+
throw(ArgumentError("Cannot access field $i since type $t only has $n_fields $field_label."))
148150
end
151+
throw_need_pos_int(i) = throw(ArgumentError("Field numbers must be positive integers. $i is invalid."))
152+
153+
t.abstract && throw_not_def_field()
149154
names = _fieldnames(t)
150155
n_fields = length(names)::Int
151-
field_label = n_fields == 1 ? "field" : "fields"
152-
i > n_fields && throw(ArgumentError("Cannot access field $i since type $t only has $n_fields $field_label."))
153-
i < 1 && throw(ArgumentError("Field numbers must be positive integers. $i is invalid."))
154-
return names[i]::Symbol
156+
i > n_fields && throw_field_access(t, i, n_fields)
157+
i < 1 && throw_need_pos_int(i)
158+
return @inbounds names[i]::Symbol
155159
end
156160

157161
fieldname(t::UnionAll, i::Integer) = fieldname(unwrap_unionall(t), i)

0 commit comments

Comments
 (0)