[Nice-info] switch(String)?
Brought to you by:
bonniot
From: Adam M. <ad...@me...> - 2004-07-04 08:56:09
|
Hi there! Both Mozilla's Rhino project as well as the XWT project (www.xwt.org) have written unsightly-but-necessary preprocessors to transform (non-Java) statements like this String s = ... switch(s) { case "bar": case "baz": into what is essentially a trie-as-code-rather-than-data: String s = ... switch(s.charAt(0)) { case 'b': switch(s.charAt(2)) { case 'r': if (s.equals("bar")) { ... } case 'z': if (s.equals("baz")) { ... } Note that s.charAt(1) is never invoked. This is generally the most efficient implementation, depending on which JVM you use; on occasion, using a hashtable lookup can perform better, but not often. Sometimes it also makes sense to switch on the length of the string first, or try == if you've been using String.intern() aggressively; these are all "tuneables" for the performance nuts. Fortunately charAt() gets inlined on any sane VM (it's final). The need for this sort of stuff comes up quite often in parsers for both languages and TCP-based, pre-XML-era protocols, and is often a performance bottleneck if implemented as a gigantic if..else..else..else block with String.equals(). More to the point: I'm interested in using Nice in general, and would be even more interested if it meant I could have one less preprocessor in my build sequence. I'd like to add this feature to Nice; is this something that (if written cleanly and properly) would be likely to make it back into the upstream source tree? In Nice's situation (direct-to-bytecode), there are further possibilities such as forcing a TABLESWITCH (both javac and jikes tend to make really stupid decisions when it comes to choosing between the two). Further generalizations might allow any 'final' field to be used as a case arm; in the case of Object derivitaves, appropriate code (in the constructor or static block) could be emitted to build a hashtable which would then be used to decide the branching path. Thanks. - a -- "The first time I read this book I felt what I could only explain as a great disturbance in the Force: it was as if a billion washing machinces all became unbalanced at once and were suddenly silenced." -- anonymous book reviewer on Amazon.com |