Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MeterArchive.fetch is ridiculously slow #3

Open
BlackCapCoder opened this issue Mar 15, 2018 · 2 comments
Open

MeterArchive.fetch is ridiculously slow #3

BlackCapCoder opened this issue Mar 15, 2018 · 2 comments
Labels
enhancement New feature or request

Comments

@BlackCapCoder
Copy link

BlackCapCoder commented Mar 15, 2018

public Meter fetch(String identification) {
for (Meter meter : meters) {
if (meter.getIdentification() == identification) {
return meter;
}
}
return null;
}

MeterArchive.fetch (and consequently all of the other methods in MeterArchive) has time complexity O(N) - this is ridiculously slow for a lookup! With as little as a couple of million meters in the archive the user would have to wait for seconds to do a lookup, and in that time they might as well go look themselves. Yuck!

There are approximately two solutions to this:

Change data-structure

Arrays are not meant for lookup, they are for fast access if you know the index of what you want. Consider switching from ArrayList to something like a HashMap that has O(1) lookup.
Have a look at the big o cheat sheet for the time complexity of different data-structures.

Be clever

If you have to store the Meters in an array, you can store them in sorted order (sorted on the reference number). Then when you want to look for a Meter you can play the number guessing game:
Take the middle meter out of the list and compare its reference number against the one you are looking for. If it is smaller/greater you repeat for the lower/upper half of the list. Continue doing this until you find an element that is equal. This has time complexity O(log N).

@olaven olaven added the enhancement New feature or request label Mar 15, 2018
@olaven
Copy link
Owner

olaven commented Mar 15, 2018

I will definitely have a look at the link later today 👍
Since this is just a small scool project and not something to be deployed as a paid service or anything, I am not sure I will worry to much about the inefficiency. That said, I enjoy (and agree with) the principle of making things as good as they can be no matter the scale of the project 😄

@BlackCapCoder
Copy link
Author

Indeed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants