Benefit from computing String Hash at compile time?

Osvaldo Pinali Doederlein opinali at gmail.com
Sun Dec 20 04:16:31 PST 2009


Em 20/12/2009 08:10, Reinier Zwitserloot escreveu:
> Huh?
>
> All you need to do is this:
>
> add a method to java.lang.String with the signature:
>
> public synthetic int switchCode() {
>     return hashCode();
> }
>
>
> Why would this cause performance issues?

This is a good idea, as long as
1) that implementation doesn't change. If it ever needs to change, we're 
again in hell, either having to recompute the switch-hash at every call, 
or wasting an extra int field in the String object to cache this 
secondary hashcode (that would be horribly wasteful because String is 
the single most popular object in most Java heaps, and only a miserably 
tiny fraction of all strings would ever be used in switchs).
2) we don't bother to tight-couple java.lang.String (remarkably with a 
public method) to the switch statement, which is a concern for some posters.

So I still think it is pointless. I say, just put in String.hashCode() 
"...and this algorithm is cast in stone, forever and ever until JDK 
+Infinity", and use it directly from switch, move on.

A+
Osvaldo

>
> --Reinier Zwitserloot
>
>
> On Sun, Dec 20, 2009 at 1:30 AM, Paul Benedict <pbenedict at apache.org 
> <mailto:pbenedict at apache.org>> wrote:
>
>     > This is wasteful, first because strings used in switch
>     statements and also
>     > in hashed collections will be hashed twice; second (and much more
>     > important), every execution switch(str) needs to call your
>     special hashcode
>     > function again for str, as this hashcode cannot be cached in
>     str. This extra
>     > cost makes switch-on-string O(N) on the str.length, which makes
>     the hashing
>     > compilation strategy pointless.
>
>     You make a good point. As for being "hashed twice", that's simply the
>     cost of removing the reliance on String.hashCode(). Well, couldn't
>     $switch_hashCode() perform some caching for itself?
>
>     Paul
>
>




More information about the coin-dev mailing list