Quantcast
Viewing all articles
Browse latest Browse all 36

What of these is the most performant way to iterate through a loop?

Which of the three approaches below is the best? Probably a dumb question but I'm always questioning myself. I could imagine that once you do more than one action with an item in a loop it would be better to cache it first but at the same time you're making a new variable each time you go through a list which makes me doubt it. Any insight on the best approach? Thanks! //This one: Note that I'm not storing a list item in a new variable for(int i = 0; i < userData.Count; i++){ if (userData[i].id == userid){ currentUserData = userData[i]; break; } } //This one: Storing in a new variable before doing multiple actions with it for (int i = 0; i < userData.Count; i++){ UserData user = userData[i]; if (user.id == userid){ currentUserData = user; break; } } //Or this one where I create the variable before looping, maybe avoiding a lot of new allocations(?) UserData user = null; for (int i = 0; i < userData.Count; i++){ user = userData[i]; if (user.id == userid){ currentUserData = user; break; } }

Viewing all articles
Browse latest Browse all 36

Trending Articles