# 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:
  ```rust
  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:
  ```sql
  SELECT * FROM tbl WHERE s2regex(tbl.col, '<reg_exp_string>') = "val";
  ```

***

Modified at: March 25, 2025

Source: [/db/v9.1/reference/code-engine-powered-by-wasm/improve-wasm-function-performance/](https://docs.singlestore.com/db/v9.1/reference/code-engine-powered-by-wasm/improve-wasm-function-performance/)

(An index of the documentation is available at /llms.txt)
