Swapping nibbles range style
Marco Leise
Marco.Leise at gmx.de
Wed Dec 11 02:27:58 PST 2013
Am Wed, 11 Dec 2013 07:19:41 +0100
schrieb "Volcz" <volcz at kth.se>:
> Are there any obvious difference between the three solutions I
> have received? They all to work the same to me.
I hope they all work the same! Depending on your background
you just might prefer one style over the other.
As an example take me. I like high efficiency so I look at the
version with
src.chunks(2).map!((a) {
auto a1 = a.front();
a.popFront();
return format("%s%s", a.front(), a1);
} )
and notice the format() function, which looks overkill to me
for a task of swapping two bytes. Then there is chunks(),
which will decode the UTF-8 string in src, which I don't need,
since there are no multi-byte characters in src. The same is
true for
return range.chunks(2).map!(
chunk => chunk.cycle.dropOne.takeExactly(2)
).joiner;
and
return s.chunks(2).map!(
c => [cast(char)c.dropOne.front, cast(char)c.front]
).join;
So I would use the second version offered by bearophile:
auto result = new char[s.length];
foreach (immutable i, ref c; result)
c = s[i + (i & 1 ? -1 : 1)];
return result;
I can easily reason about it from looking at it. It makes one
allocation "new char[s.length]" and does no UTF-8 decoding.
--
Marco
More information about the Digitalmars-d-learn
mailing list