Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Andreas Leitgeb Newsgroups: comp.lang.java.machine Subject: Re: new String ( char[] ) Date: Sun, 27 Apr 2014 16:50:29 +0000 (UTC) Organization: A noiseless patient Spider Lines: 40 Message-ID: References: Reply-To: avl@logic.at Injection-Date: Sun, 27 Apr 2014 16:50:29 +0000 (UTC) Injection-Info: mx05.eternal-september.org; posting-host="7fd0c836d94caf9f0b88d96117d7c68e"; logging-data="1414"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+Tz4rdjSPdZALg5YAPiBgG" User-Agent: slrn/pre1.0.0-18 (Linux) Cancel-Lock: sha1:B7YCrhqjied/+t/4aF3F20Fsrbo= Xref: csiph.com comp.lang.java.machine:47 Roedy Green wrote: > For some reason it bothers me deeply that new String ( char[] ) > requires making a copy of the char array and then setting a pointer in > the String object to it. > > Why not just point to the existing char[]? I don't need it any more. > > The problem is the JVM does not know for sure than that there are no > other references to that char[]. The referencers would then have > access to modify the char[] inside an immutable String object, a > strong no no. Often these topics are quickly turned down with the killer phrase "pre-mature optimization" but just recently I was able to improve performance by a factor of five by no longer relying on the magic powers of JIT, but instead doing some lowlevel optimizations regarding StringBuilder's capacity and avoiding a lot of toString()'s when putting characters from various sources into a target StringBuilder. Maybe, it wasn't pre-mature in my case, although some people claim that it is always "pre-mature" regardless of the circumstances. > There must be a way of getting the same effect without that whacking > huge copy. It might be megabytes long. Make your own library, that accepts StringBuilders/CharSequences instead of Strings. To your own classes add a method toCharSeq() that will bypass creation of String and its inevitable copying, if all you needed the String for was having it appened to a StringBuilder. Also, if you're dealing with long strings and concatenating them, then its likely to be worth the effort predetermining the total size and using StringBuilder's ensureCapacity() beforehand, but I guess you already do that with your Fast StringBuilder that you mentioned in comp.lang.java.programmer a while ago. > Can anyone think of a JVM implementation that could avoid that copy? I for myself wouldn't bet on that horse.