LoginSignup
8
2

More than 1 year has passed since last update.

Elixirの文字列結合はiolistとして処理した方が高速らしい

Last updated at Posted at 2021-09-21

Elixir文字列結合にはいくつかの方法あります
iolistとして処理すると効率よく文字列結合できるそうです

IO.puts/2を使った例

a = "Hello"
b = "World"

# binary 1
IO.puts( a <> " " <> b )

# binary 2
IO.puts( "#{a} #{b}" )

# iolist 1
IO.puts( [a, " ", b] )

# iolist 2
IO.puts( :io_lib.format("~s ~s", [a, b]) )

# 結果は同じ
Hello World
:ok

:io_lib.format/2は使い方によってはコードを見やすくできる場合があるとおもいます
記号の意味は:io.fwrite/3のドキュメントにあります
例としてNervesMOTDのコードでいくつか出てきます

EExを使った例

a = "Hello"
b = "World"

# binary 1
EEx.compile_string("<%= a <> \" \" <> b %>") |> Code.eval_quoted(a: a, b: b)

# binary 2
EEx.compile_string("<%= \"#{a} #{b}\" %>") |> Code.eval_quoted(a: a, b: b)

# iolist 1
EEx.compile_string("<%= [a, \" \", b] %>") |> Code.eval_quoted(a: a, b: b)

# iolist 2
EEx.compile_string("<%= :io_lib.format(\"~s ~s\", [a, b]) %>") |> Code.eval_quoted(a: a, b: b)

# 結果は同じ
{"Hello World",
 [{:b, "World"}, {{:arg0, EEx.Engine}, "Hello World"}, {:a, "Hello"}]}
8
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
2