I'm working on an Android Application using Java and I was wondering about performance regarding declaring new variables.
Disclaimer: I'm not an expert in Java, so I don't really know how things work on lower levels.
In these two snippets of code below:
for(int i = 0; i < getApplication().getUsers().size(); i++) {
if(getApplication().getUsers().get(i).getId() == id) {
return getApplication().getUsers().get(i);
}
}
.
int size = getApplication().getUsers().size();
for(int i = 0; i < size; i++) {
User user = getApplication.getUsers().get(i);
if(user.getId() == id) {
return user;
}
}
Would it have any performance difference between them?
I think the second is more readable and clean, but I end up declaring more variables.
I'm lean to think that when I'm declaring more variables, I will need more memory to store them. In the other hand, accessing deep nested object could cause an increasing in CPU usage (maybe?). Is any of that true? Or at least makes sense?
Is there any best practices regarding declaring variables or accessing them direct from objects?
Thanks!