[erlang-questions] Question about lists:filter
Richard A. O'Keefe
Fri Aug 30 03:01:47 CEST 2013
On 30/08/2013, at 1:52 AM, David Mercer wrote:
> Curiously enough, though, timingwise the following 2 seem to do roughly the same:
> is_palindrome1(X) ->
> integer_to_list(X) == lists:reverse(integer_to_list(X)).
> is_palindrome2(X) ->
> Digits = integer_to_list(X),
> Digits == lists:reverse(Digits).
Presumably integer_to_list/1 does the bulk of its work in C.
There are two kinds of cost involved in code like this: the
time it takes to build the garbage and the space the garbage
takes. The two versions both create 3N list cells which
almost instantly become garbage.
The most space-efficient (and the most time-efficient) method,
at least for unboxed integers, is to do the palindrome test
with arithmetic, not using lists at all.
original code: 9.88 seconds (integer_to_list twice, reverse once)
revised list: 3.06 seconds (integer_to_list once, pattern match)
arithmetic: 2.14 seconds (no lists at all)
More information about the erlang-questions