The task to "translate a string through a table" is common. It is a single
computer instruction (TR) in the IBM 360 and was extended over time with
related instructions for conversion in and out of UTF-8, testing before and
after translation, and expanded character sizes. Tamás Gulácsi's approach
would be mine too.

On Thu, Aug 30, 2018 at 5:30 AM Marvin Renich <m...@renich.org> wrote:

> * Tamás Gulácsi <tgulacs...@gmail.com> [180830 01:17]:
> > An even faster lookup is creating a [256]byte array for the
> replacements,
> > having the 9 replacements candidates _position_ having the replacements,
> > all others the identity:
> >
> > // prepare the lookup table
> > var a [256]byte
> > for i := 0; i<256; i++ {
> >   a[i] = i
> > }
> > a[37] = '-'
> > a[129] = '-'
> > ...
> >
> > // replace the bytes, in-place operation
> > func replace(p []byte) {
> >   for i, b := range p {
> >     p[i] = a[b]
> >   }
> > }
> >
> > Although map lookup is O(1), array lookup is O(1) with a smaller
> constant
> > factor, I'm sure.
> > And this has no branching, so should be even faster.
>
> I'm not convinced, and only benchmarking will tell.  If len(p) == 100
> and only six of those are in the set to be replaced, doing 100 memory
> writes instead of branching and doing six memory writes might very well
> be slower.
>
> Today's hardware has all sorts of optimizations that help with both
> cases.  Predictive branching and caching will each help with one of the
> two approaches.  You can't be sure until you have benched with realistic
> data.
>
> I would, however, replace the map in the previous suggestion with a
> [256]int16 with -1 meaning "don't replace".  This is really just a
> special-case optimized map.  If 0 is not a valid replacement byte, use
> [256]byte with 0 meaning "don't replace".
>
> ...Marvin
>
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
>


-- 

*Michael T. jonesmichael.jo...@gmail.com <michael.jo...@gmail.com>*

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to