Like other programming languages, Julia also provides support for Serialization and De-serialization. The process of conversion of an object into byte streams (IO buffers) for the purpose of storing it into memory, file, or database is termed as Serialization. It is performed to save the object state for later use. The reverse process is termed as De-serialization.
Methods to Perform Serialization in Julia:
- Serialization is achieved by the Serialization module present in Julia.
- JLD2 module in Julia saves and loads Julia data structures in a format containing a subset of HDF5, without being dependent on the HDF5 C library. It outperforms Julia’s built-in serializer.
- BSON module can also be used to provide the feature of serialization.
Serialization.serialize() Function
Syntax:
serialize(stream::IO, value)
and
serialize(filename::AbstractString, value)
Serialization.deserialize() Function
Syntax:
deserialize(stream)
and
deserialize(filename::AbstractString)
Note:
- serialize and deserialize functions perform read and write operations using iobuffer object. IOBuffer acts as an in-memory I/O stream.
- The function take! fetches iobuffer contents as a byte array and resets it to its initial state.
Performing Serialization using various modules
Using Serialization Module:
Julia
using Serialization
io = IOBuffer();
arr = [ 1 , 2 , 3 , 4 , 5 ];
serialize(io, arr)
print (take!(io))
|
Output:
Using JLD2 Module:
Julia
using JLD2
using FileIO
arr = [ 1 , 2 , 3 , 4 , 5 ];
file = File ( format "JLD2" , "array.jld2" )
save( file , "arr" , arr)
data = load( file )
dump(data[ "arr" ])
|
Output:
Using BSON Module:
Julia
using BSON
bson( "test.bson" ,
Dict (:arr = > [ 1 , 2 , 3 , 4 , 5 ],
: str = > "GfG!" ))
BSON.load( "test.bson" )
|
Output:
Performing De-serialization using Serialization Module
Julia
using Serialization
io = IOBuffer();
arr = [ 1 , 2 , 3 , 4 , 5 ];
serialize(io, arr)
s = take!(io);
ds = deserialize(IOBuffer(s));
print (ds)
|
Output:
Last Updated :
12 Oct, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...