Improve Wasm Function Performance
Here are some examples of ways to improve the performance of your Wasm code:
-
Compile the Wasm function in "release" mode and not in debug mode.
To compile in release mode, -
In Rust, pass the
--release
flag to cargo, and -
In C/C++, pass the
-O3
option to the compiler.
-
-
If your program can benefit by building data structures in advance, you may improve performance by maintaining a cache in your Wasm program.
For example, you can cache reusable data between function calls. The following example caches compiled regular expressions so it does not have to compile the regular expression argument again for every row passed to the function:
wit_bindgen_rust::export!("s2regex.wit");use regex::Regex;use std::cell::RefCell;use std::collections::HashMap;struct S2regex;thread_local! {static COMPILED_RGXS: RefCell<HashMap<String, Regex>> = RefCell::new(HashMap::new());}impl s2regex::S2regex for S2regex {fn capture(input: String, pattern: String) -> String {COMPILED_RGXS.with(|c| {let mut map = c.borrow_mut();let re = map.entry(pattern).or_insert_with_key(|pattern| Regex::new(pattern).unwrap());re.captures(&input).and_then(|c| c.get(1)).map(|c| c.as_str()).unwrap_or_default().to_string()})}}The following query has to compile the regular expression only for the first row:
SELECT * FROM tbl WHERE s2regex(tbl.col, '<reg_exp_string>') = "val";
Last modified: March 25, 2025