Parsing null terminated strings in a binary.
Per Gustafsson
per.gustafsson@REDACTED
Thu Jan 13 16:46:19 CET 2005
I tested some different versions of the z_split program and the fastest
one I found was this:
z_split(B) when is_binary(B) ->
z_split3(B, 0, size(B)).
z_split3(B, N, X) ->
case B of
<<_:N/binary,0,_/binary>> ->
<<B1:N/binary,0,B2/binary>> = B,
{B1,B2};
_ when X > N ->
z_split3(B, N+1, X);
_ ->
B
end.
This moves the call to size outside the loop and it also avoids creating a
subbinary unless an actual zero has been found.
If you hipe compile the code however this is the fastest version:
z_splita(B) when is_binary(B) ->
z_splita2(B, 0).
z_splita2(B,N) ->
case B of
<<_:N/binary,0,_/binary>> ->
<<B1:N/binary,0,B2/binary>> = B,
{B1,B2};
<<_:N/binary>> ->
B;
_ ->
z_splita2(B, N+1)
end.
About 3.5 times faster than the non hipe compiled version
Per
On Thu, 13 Jan 2005, Mats Cronqvist wrote:
> 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.
> >
> >
>
More information about the erlang-questions
mailing list