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?

wohlstad's user avatar

wohlstad

36.8k18 gold badges79 silver badges113 bronze badges

CocoaMix86's user avatar

1

You can use pattern matching with variable assignment:

return listOfObjects[Index] is { param1: "test1", param2: "test2" } theObject ? theObject : null;

Charlieface's user avatar

2 Comments

Is there an alternative to this that allows for swapping "test1" "test2" with variables? Pattern matching doesn't allow for non-constant comparisons.

2026-01-12T22:33:14.46Z+00:00

Well you could just do the pattern + variable and then comparisons after, like return listOfObjects[Index] is { } theObject && theObject.param1 == test1 && theObject.param2 == test2 ? theObject : null; but that isn't much shorter than the other answer.

2026-01-13T01:19:16.01Z+00:00

You can store a reference to listOfObjects[Index] in a variable,
and then use it multiple times:

var elem = listOfObjects[Index]; return elem.param1 == "test1" && elem.param2 == "test2" ? elem : null;

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.

wohlstad's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.