ARTICLE AD BOX
I have a line of code like so:
return listOfObjects[Index].param1 == "test1" && listOfObjects[Index].param2 == "test2" ? listOfObjects[Index] : null;Instead of referencing listOfObjects[Index] 3 times, is there some shorthand to reference it only 1 time and "re-use" it for the rest of the line? If it exists, is it performance enhancing to do so, or does 3 calls to a list for the same object not affect much?
36.8k18 gold badges79 silver badges113 bronze badges
1
You can use pattern matching with variable assignment:
return listOfObjects[Index] is { param1: "test1", param2: "test2" } theObject ? theObject : null;79.2k8 gold badges36 silver badges77 bronze badges
2 Comments
You can store a reference to listOfObjects[Index] in a variable,
and then use it multiple times:
Note that if your list elements are of value type (e.g. a struct), elem here will be a copy of the element.
Regarding performance enhancement:
I doubt it will matter much (at least with the posted example). But as with all issues of performance: you should profile your code and check.
36.8k18 gold badges79 silver badges113 bronze badges
Explore related questions
See similar questions with these tags.
