|
1 | 1 | # Serializing and Deserializing Arbitrary Data Into and From `JsValue` with Serde
|
2 | 2 |
|
3 | 3 | It's possible to pass arbirtrary data from Rust to JavaScript by serializing it
|
4 |
| -with [Serde](https://github.com/serde-rs/serde). `wasm-bindgen` includes the |
5 |
| -`JsValue` type, which streamlines serializing and deserializing. |
| 4 | +to JSON with [Serde](https://github.com/serde-rs/serde). `wasm-bindgen` includes |
| 5 | +the `JsValue` type, which streamlines serializing and deserializing. |
6 | 6 |
|
7 | 7 | ## Enable the `"serde-serialize"` Feature
|
8 | 8 |
|
@@ -105,3 +105,23 @@ example.field2.push([5,6]);
|
105 | 105 | // Send the example object back to wasm.
|
106 | 106 | receive_example_from_js(example);
|
107 | 107 | ```
|
| 108 | + |
| 109 | +## An Alternative Approach: `serde-wasm-bindgen` |
| 110 | + |
| 111 | +[The `serde-wasm-bindgen` |
| 112 | +crate](https://github.com/cloudflare/serde-wasm-bindgen) serializes and |
| 113 | +deserializes Rust structures directly to `JsValue`s, without going through |
| 114 | +temporary JSON stringification. This approach has both advantages and |
| 115 | +disadvantages. |
| 116 | + |
| 117 | +The primary advantage is smaller code size: going through JSON entrenches code |
| 118 | +to stringify and parse floating point numbers, which is not a small amount of |
| 119 | +code. |
| 120 | + |
| 121 | +There are two primary disadvantages. The first is that it is not always |
| 122 | +compatible with the default JSON-based serialization. The second is that it |
| 123 | +performs more calls back and forth between JS and Wasm, which has not been fully |
| 124 | +optimized in all engines, meaning it can sometimes be a speed |
| 125 | +regression. However, in other cases, it is a speed up over the JSON-based |
| 126 | +stringification, so — as always — make sure to profile your own use |
| 127 | +cases as necessary. |
0 commit comments