Complexity of enum.values()

让人想犯罪 __ 提交于 2020-01-16 13:12:08

问题


I have a very simple Enum as follows:

public enum Colour { RED, BLUE, GREEN; }

Here I've put three colours, but it may have a undefined size.

This Enum will be used in a class which can have an undefined number of instances (hundreds, thousands or even millions).

In this class I have a method that must return a random Colour.

I have two options for this.

private Colour[] colours;

public Datastructure() {

    colours = Colour.values();
}

public Colour getRandomColour() {
     return colours[rand.nextInt() % colours.length];
}

Or I can keep calling Colour.values() instead of creating the colours list.

public Colour getRandromColour() {
     return Colour.values()[rand.nexInt() % Colour.values().length]

In the first option, an extra array is created. Keep in mind that this class may have many instances, so it could be considered a waste of memory, and may have a impact on running time as well (instantiating the array). Especially when there are a lot of class instances.

In the second option, Colour.values() is called a few times (in this simple example it is only a few times but in my project it's bit more complex and has more calls) so this can be considered a waste of CPU usage.

I would prefer using the second option, but I'm curious about the complexity of the Colour.values() method, which I fear may be linear O(n). n being the number of Colours in the enum. This would be horrible when there are a lot of colours.

Or would it just be a weigh off and choose the best of two evils?

tl;dr What is the complexity of Enum.values()?


回答1:


The array returned by Colour.values() always contains the same elements, but values() creates a new array every time it's called (so it's O(n) where n is the number of enum values). And you never modify that array. So calling the method every time you need it is a waste of time. And storing an array in every instance of your DataStructure class is a waste of time and memory. I would simply call the method once and cache that array in a constant:

private static final Colour[] COLOURS = colour.values();

public Colour getRandomColour() {
    return COLOURS[rand.nextInt(COLOURS.length)];
}

Just make sure this array is never exposed outside of the class.

Also note the usage of Random.nextInt(limit) which does exactly what you want, is probably faster, and expressed the intent more clearly than using a modulo.




回答2:


Why not just put the cached array in a static field of Colour enum itself. then provide a method in the Colour enum to return a random entry.

It makes sense for the Colour enum to own this piece of data/method anyway.



来源:https://stackoverflow.com/questions/27089438/complexity-of-enum-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!