RockyMountainHigh
RockyMountainHigh

Reputation: 3021

Erlang string:join vs io_lib:format

I have a bit of code where I am taking 4 values and joining them with a pipe ("|"). currently it is implemented in the following manner:

lists:flatten(io_lib:format("~s~s~s~s~s",[Id, Delim, Date, Delim, Signature])).

But, I'm wondering if there is any advantage to changing to use string:join (other than it appears cleaner)?

Upvotes: 2

Views: 676

Answers (3)

I GIVE CRAP ANSWERS
I GIVE CRAP ANSWERS

Reputation: 18859

Just using

 [Id, $|, Delim,
      $|, Date,
      $|, Delim,
      $|, Signature]

could be valid since it is an iolist() already. So you don't have to send it through anything. The data is already the concatenation you seek. Manipulating the data and flattening it for the sake of doing so is most often a mistake which at best wastes clock cycles and uses more memory resources.

Upvotes: 1

Ward Bekker
Ward Bekker

Reputation: 6366

Although string:join([Id,Date,Signature],"|"). and lists:flatten(io_lib:format("~s~s~s~s~s",[Id, Delim, Date, Delim, Signature])). give the same result, string:join is preferred, because has better readability:

  • The name of the function describes the actual intent.
  • It's concise, so the reader is less distracted by verbosity.

Readability is paramount, as code is often read many, many times during a project

Upvotes: 4

Jan Henry Nystrom
Jan Henry Nystrom

Reputation: 1065

It would be marginally faster but more importantly easier to read, and as I always claim "Clarity is king."

Upvotes: 2

Related Questions