erlang binary資料轉換的問題,erlangbinary
erlang提供了binary_to_term,把一個位元據轉為原始的erlang資料。但是,這個函數也有副作用。如果直接將對端傳來的資料做一次 binary_to_term,就可能會導致VM crash掉。
binary_to_term 副作用
這是因為位元據帶有原子時,binary_to_term會產生這些原子。但VM原子總數是有限制,而且原子不參與GC。假如資料帶有原子數量超過erlang VM限制,就會導致VM crash
所以,針對這個問題,erlang提供了另外一個函數 binary_to_term(Binary, [safe]),這個函數不會產生新的的原子,在這點上,這兩個函數關係也像 list_to_atom 和 list_to_existing_atom
1> term_to_binary(atom).<<131,100,0,4,97,116,111,109>>2> binary_to_term(v(1), [safe]).atom3> binary_to_term(v(1)).atom4> binary_to_term(<<131,100,0,4,116,101,115,116>>, [safe]).%%這裡會拋出異常** exception error: bad argument in function binary_to_term/2 called as binary_to_term(<<131,100,0,4,116,101,115,116>>,[safe])5> binary_to_term(<<131,100,0,4,116,101,115,116>>).test6> binary_to_term(<<131,100,0,4,116,101,115,116>>, [safe]).%%這裡就不會拋出異常test
term_to_binary二進位壓縮
與binary_to_term相反,term_to_binary 則是把erlang資料轉成一個位元據。預設情況下,term_to_binary後的位元據是不經過壓縮的,比較大,erlang也提供了另外一個函數,用於壓縮產生的位元據。
term_to_binary(Term, [{compressed, Level}]
Level 取值範圍1-9,表示壓縮率,1是壓縮比最低,但最少消耗時間,9是最高壓縮比。 也可以是0,表示不壓縮。
實際上,1已經能滿足要求,又不會太消耗時間。而且,term_to_binary/2壓縮後的二進位對 binary_to_term 影響不大
另外,term_to_binary做二進位壓縮,必然帶有一定的開銷,但比term_to_binary後使用 zlib:zip 壓縮資料來說,開銷就小了很多,而且接收端還要zlib:unzip資料。顯然term_to_binary/2 是在注重流量的場合比較適合。
參考:http://blog.csdn.net/mycwq/article/details/42622193