0

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!

Thiago Loddi
  • 2,212
  • 4
  • 21
  • 35
  • Nope, it doesn't affect performance. At least you shouldn't worry about it. Btw you could use list iterator withing for `for (User user: getApplication.getUsers()) { ... }` – deathangel908 Nov 28 '17 at 17:52
  • There is no performance based difference between these two: In first snippet you are using direct functions instead of storing the returned value of those functions as you did in second snippet. – Lalit Verma Nov 28 '17 at 17:52
  • in some case the value could change between getter calls (that's a possibility) –  Nov 28 '17 at 17:53
  • Thank for the input! @RC I had already seen the answer you marked as duplicate, but I didn't think it answered my question (so I wrote this one). Maybe for beginners like me, it's not so clear that they are talking about the same thing. – Thiago Loddi Nov 28 '17 at 17:57
  • "more variables, I will need more memory" - No. But even if it was the case, it means four more bytes during the execution of your method (it's just a reference to an object). See also [this answer of mine](https://stackoverflow.com/a/19446785/581205). – maaartinus Nov 29 '17 at 10:46

0 Answers0