switch(String)?
Adam Megacz <[email protected]> Sat, 03 Jul 2004 19:37:38 -0700
| Newsgroups | gmane.comp.lang.nice.general |
|---|---|
| Organization | Myself |
| Message-ID | <m1fz88v6od.fsf__36470.2397528619$1088931669$gmane$org@nowhere.com> |
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
-------------------------------------------------------
This SF.Net email sponsored by Black Hat Briefings & Training.
Attend Black Hat Briefings & Training, Las Vegas July 24-29 -
digital self defense, top technical experts, no vendor pitches,
unmatched networking opportunities. Visit www.blackhat.com