length of an iolist
Mark Scandariato
mfs@REDACTED
Fri Aug 12 17:32:40 CEST 2005
How would iolist_to_binary differ from list_to_binary?
Here are two versions of iolist_size I put together - an erlang version and a bif.
-module(tst).
-export([i_size/1]).
i_size(L) -> i_size(L, 0).
i_size([], S) -> S;
i_size([H|T], S) when is_binary(H) ->
i_size(T, S+size(H));
i_size([H|T], S) when H >= 0, H =< 255 ->
i_size(T, S+1);
i_size([H|T], S) when is_list(H) ->
i_size(T, S) + i_size(H);
i_size(_, _) -> erlang:error(badarg).
This is a cut, paste, hack of list_to_binary_1 (inspired by Ulf Wiger's erlang:push_element/1):
BIF_RETTYPE iolist_size_1(BIF_ALIST_1)
{
Eterm bin;
int i;
if (is_nil(BIF_ARG_1)) {
BIF_RET(SMALL_ZERO);
}
if (is_not_list(BIF_ARG_1)) {
error:
BIF_ERROR(BIF_P, BADARG);
}
if ((i = io_list_len(BIF_ARG_1)) < 0) {
goto error;
}
BIF_RET(make_small_or_big(i, BIF_P));
}
Here's how they perform on an iMac G5 (1.6GHz, Mac OS X 10.4.2) with R10B-6 (L is a list of nested lists and binaries, not terribly deep - maybe 3 levels of nesting):
111> erlang:garbage_collect(), timer:tc(tst, i_size, [L]).
{23318,51000}
112> erlang:garbage_collect(), timer:tc(erlang, iolist_size, [L]).
{359,51000}
Mark.
More information about the erlang-questions
mailing list