Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!aioe.org!eternal-september.org!feeder.eternal-september.org!.POSTED!not-for-mail From: markspace <-@.> Newsgroups: comp.lang.java.programmer Subject: Re: Using Enumerated Types as Array Indexes Date: Thu, 18 Aug 2011 14:48:48 -0700 Organization: A noiseless patient Spider Lines: 40 Message-ID: References: <4e4b0d81$0$314$14726298@news.sunsite.dk> <4e4b1fe4$0$314$14726298@news.sunsite.dk> <6d418cda-dab3-43df-a9ec-293b43f2bbd8@glegroupsg2000goo.googlegroups.com> <9b2aglFuj7U1@mid.individual.net> <__-dnaxcSIRV-NHTnZ2dnUVZ_tOdnZ2d@earthlink.com> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Thu, 18 Aug 2011 21:48:58 +0000 (UTC) Injection-Info: mx04.eternal-september.org; posting-host="XjIWM99mD7Ijfdu600oVPA"; logging-data="9741"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18ro1LVnuQ3y4Zzj+V+p1p2p69arOKM7lA=" User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20110812 Thunderbird/6.0 In-Reply-To: Cancel-Lock: sha1:kP5PwTNRvSjTGFrHXWAH+zlhdFo= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:7230 On 8/18/2011 1:49 PM, Andreas Leitgeb wrote: > markspace<-@> wrote: >> On 8/18/2011 11:37 AM, Andreas Leitgeb wrote: >>> Apart from that, it is a dirty hack to avoid conditionals. >> >> One thing to keep in mind here I think is the relative execution time >> for each operation: [...] >> >> So preferring modulus to ?: or Math.abs() might be a misoptimization. > > Math.abs() does an entirely wrong job for the original context. > > Now, let's say N is the array's length, and n the result > from the latest increment: > > ( n % N + N ) % N > versus > ( n % N< 0 ) ? n % N + N : n % N > or with an helper var r: > ( ( r = n % N )< 0 ) ? r + N : r > > PS: I didn't previously say *why* I avoided conditionals. Yeah, your requirements are unspecified. I was thinking: arr[ Math.abs( n % N ) ] Would at least prevent overflow, although I don't think it would provide a strictly incrementing index for arr. Or you could just strip off the sign bit: arr[ (n&0x7FFFFFFF) % N ] That gets rid of those pesky negative numbers right quick. Though I'm still not convinced that this is "better."