erlang binary資料轉換的問題,erlangbinary

來源:互聯網
上載者:User

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


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.