java - Best Method to Initialise Complex Static Values -


i have class may need large, unchanging, data-structure based on contents of enum class.

what i'm interested know whether better me initialise in static block, or should initialise within method accesses data (in case it's never used)?

here's example:

public enum myenum {     foo ("foo"),     bar ("bar"),     foobar ("foo_bar");      private final string othername;      private myenum (string othername) {         this.othername = othername;     }      private static final map<string, myenum> othernames = new hashmap<string, myenum>(); } 

now, have 2 options initialising othernames map, first being use static block so:

static {     (myenum entry : myenum.values())          othernames.put(entry.othername, entry); } public static myenum valuebyothername (string othername) {     return othernamesstatic.get(othername); } 

or alternatively can initialise map first time lookup requested like-so:

public static myenum valuebyothername(string othername) {     if (othernames.isempty()) { // or test against null or whatever         (myenum entry : myenum.values())             othernames.put(entry.othername, entry);     }     othernames.get(othername); } 

in particular i'm interested know whether java optimise static block such can pre-generate map on future runs (since it's based on enum if hasn't changed, neither has map) or run static code every time class loads, in case doing when needed may more efficient?

as long understand java, classloader calls static initialization block @ moment loads class , @ moment. :

  • if using static block, sure called @ least once if use class myenum if not use valuebyothername , never called again until jvm closed (unless have independant classloaders loading same class should @ least strange). have no test in valuebyothername
  • if using initialization on first lookup, block called if call valuebyothername , construction never called again. have test in each call valuebyothername

imho far better use static block. , far more readable ...


Comments

Popular posts from this blog

php - render data via PDO::FETCH_FUNC vs loop -

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

The canvas has been tainted by cross-origin data in chrome only -