0

In my program (Bayes classifier), I have a lot of calls to the map.size() method.

I was wondering if the performance of the program can be optimized by storing the value of map.size() in a local variable (or a field).

If so, what would be the right way to store it in a variable?

int mapSize = map.size();

Below the surface, this will probably just create a pointer to the method (?)

Lucas
  • 229
  • 1
  • 3
  • 8
  • 4
    In most map implementations, size() is O(1), and simply returns the value of a field. Storing it in a variable most probably won't change anything. Don't try random things to optimize your code. Measure (that's hard, but necessary), and then concentrate on the parts that actually take time. – JB Nizet Dec 15 '18 at 10:29
  • 1
    A `Map` needs to know its `size()` so (in most implementations) it's already sorted internally. Storing it externally means that you'd need to add a whole lot of invalidate/update logic. If your `Map` never changes you can likely reap large benefits from switching to an immutable `Map` implementation. As with all micro-optimisations this is a generalisation, without running microbenchmarks against your code you will never get a definitive answer. – Boris the Spider Dec 15 '18 at 10:32
  • Which map implementation are you using? – Mark Dec 15 '18 at 10:43

1 Answers1

2

The code below which is provided in your question would not store a pointer to the method, it stores the value that method returned.

int mapSize = map.size();

Looking at the HashMap.size(); method you can see it just returns a local variable, which is causing it to be really fast already:

/**
 * Returns the number of key-value mappings in this map.
 *
 * @return the number of key-value mappings in this map
 */
public int size() {
    return size;
}
Mark
  • 5,089
  • 2
  • 20
  • 31
  • As both JBNizet and I point out in comments this is an implementation detail and depending on the specific `Map` implementation user the latter half of your answer is potentially false. – Boris the Spider Dec 15 '18 at 10:36