Parsing null terminated strings in a binary.
Raimo Niskanen
raimo@REDACTED
Thu Jan 13 17:19:00 CET 2005
Sorry, I am also to lazy to measure.
It is probably so that yours
> z_split(B, N) ->
> case B of
> <<B1:N/binary,0,B2/binary>> -> {B1, B2};
> <<_:N/binary>> -> B;
> _ -> z_split(B, N+1)
> end.
is faster than mine
> z_split(B, N) when is_binary(B), is_integer(N) ->
> case B of
> <<B1:N/binary,0,B2/binary>> ->
> {B1,B2};
> _ when size(B) > N
> z_split(B, N+1);
> _ ->
> B
> end.
since the second clause in the first variant is done in a binary
pattern matching context, and there is a setup cost, so the
second clause may be very cheap; at least probably cheaper than
calling size/1 (after the binary pattern matching).
It might even be so cheap that moving the size(B) call outside
the loop in variant 2 does not give any measurable improvement
over variant 1. You will have to compare Size with N in the loop
in that case. And for hardcore optimization the is_binary(B) and
is_integer(N) should be moved outside the loop, of course.
So, allright, your suggested variant may be the winner!
Messen ist vissen. (Werner von Siemens) # To measure is to know.
mats.cronqvist@REDACTED (Mats Cronqvist) writes:
> sorry to keep harping on this...
> ...but would it be (noticably) faster to move the call to size/1 outside the loop?
> or equivalently, how fast is size/1 (compared to the binary match)?
> i would guess plenty fast but i'm too lazy to try it.
>
> mats
>
> Raimo Niskanen wrote:
> > You are missing nothing. The code just evolved in my head to
> > what it became - some cruft was left. This might be even clearer
> > (untested):
> > z_split(B, N) when is_binary(B), is_integer(N) ->
> > case B of
> > <<B1:N/binary,0,B2/binary>> ->
> > {B1,B2};
> > _ when size(B) > N
> > z_split(B, N+1);
> > _ ->
> > B
> > end.
> >
--
/ Raimo Niskanen, Erlang/OTP, Ericsson AB
More information about the erlang-questions
mailing list