[erlang-questions] Better use of io:format and io_lib:format

Michael Richter ttmrichter@REDACTED
Thu Oct 1 14:55:29 CEST 2009


You could try an experiment, maybe?

File: "output":

#! /usr/bin/env escript
%% -mode(compile).

main(["list"]) ->
    M1 = erlang:process_info(self(), memory),
    T1 = erlang:now(),
    list_loop(500),
    T2 = erlang:now(),
    M2 = erlang:process_info(self(), memory),
    io:format("~n~n~w , ~w , ~w~n~n", [M1, M2, timer:now_diff(T2,T1)]);

main(["binary"]) ->
    M1 = erlang:process_info(self(), memory),
    T1 = erlang:now(),
    binary_loop(500),
    T2 = erlang:now(),
    M2 = erlang:process_info(self(), memory),
    io:format("~w , ~w , ~w~n", [M1, M2, timer:now_diff(T2,T1)]);

main(_) ->
    io:format("Try again.~n").

list_loop(0) ->
    io:format("Done!~n~n");

list_loop(N) ->
    io:format("hello ~s", ["world"]),
    list_loop(N-1).

binary_loop(0) ->
    io:format(<<"Done!~n~n">>);

binary_loop(N) ->
    io:format(<<"hello ~s">>, [<<"world">>]),
    binary_loop(N-1).

Result set from several runs of "clear ; ./output list":

   - {memory,54492} , {memory,33820} , 104308
   - {memory,54492} , {memory,33820} , 103686
   - {memory,54492} , {memory,33820} , 100892
   - {memory,54492} , {memory,33820} , 87483
   - {memory,54492} , {memory,33820} , 99644

Result set from several runs of "clear ; ./output binary":

   - {memory,44156} , {memory,33820} , 94222
   - {memory,44156} , {memory,33820} , 110587
   - {memory,44156} , {memory,33820} , 115329
   - {memory,44156} , {memory,33820} , 111326
   - {memory,44156} , {memory,33820} , 102580

I make no representation that my code is any good (indeed it's the
opposite), but a brief eyeball of the results shows that binaries use up a
little less memory and a little more CPU.  I'm certain the other, better
Erlang users can give you better benchmarking code to answer your question
(but so can you, and your benchmarking code would reflect your intended
use).

2009/10/1 Bernardo Alvez <manprog@REDACTED>

> Hi all,
>
> Which  of the following is better to use in terms of performance and
> resources usage?:
>
> io:format("hello ~s", ["world"]).
> or
> io:format(<<"hello ~s">>, [<<"world">>]).
>
> Thanks,
> Bernardo
>
> ________________________________________________________________
> erlang-questions mailing list. See http://www.erlang.org/faq.html
> erlang-questions (at) erlang.org
>
>


More information about the erlang-questions mailing list