Erlang/OTP Forums

Author Message

<  Erlang  ~  Fast binary replace

ArtDen
Posted: Sat Dec 20, 2008 5:36 pm Reply with quote
Joined: 01 Nov 2008 Posts: 4
I wrote function for replacement of data in binaries:
Code:
bin_replace(What, From, To) ->
    bin_replace(What, erlang:byte_size(From), What, From, To, <<>>).
   
bin_replace(WhatOrig, FromLen, What, From, To, Acc) ->
    case What of
        <<From:FromLen/binary, Other/binary>> ->
            OtherRepl = bin_replace(Other, From, To),
            <<Acc/binary, To/binary, OtherRepl/binary>>;
       
        <<Char:8, Other/binary>> ->
            bin_replace(WhatOrig, FromLen, Other, From, To, <<Acc/binary,Char>>);
       
        <<>> ->
            WhatOrig
    end.
Code:
test() ->
    Data = <<"string to replace. lalala, lalala">>,
    From = <<"lalala">>,
    To = <<"wow">>,
    Result = bin_replace(Data, From, To),
    io:format("Result=~p~n", [Result]).
but I think there are other ways to do same faster. Does anyone know this ways?
View user's profile Send private message
ArtDen
Posted: Sat Dec 20, 2008 6:01 pm Reply with quote
Joined: 01 Nov 2008 Posts: 4
I did it little faster (~30 of speed is increased) by getting rid of accumulate right string part:
Code:
bin_replace2(What, From, To) ->
    bin_replace2(What, erlang:byte_size(From), What, From, To, 0).

bin_replace2(WhatOrig, FromLen, What, From, To, Cnt) ->
    case What of
        <<From:FromLen/binary, Right/binary>> ->
            OtherRepl = bin_replace2(Right, From, To),
            <<Left:Cnt/binary,_/binary>> = WhatOrig,
            <<Left/binary, To/binary, OtherRepl/binary>>;
       
        <<_:8, Other/binary>> ->
            bin_replace2(WhatOrig, FromLen, Other, From, To, Cnt+1);
       
        <<>> ->
            WhatOrig
    end.

Any other ideas?
View user's profile Send private message

Display posts from previous:  

All times are GMT
Page 1 of 1
This forum is locked: you cannot post, reply to, or edit topics.

Jump to:  

You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You cannot download files in this forum