Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

性能疑问 #214

Closed
lijialiang opened this issue Dec 6, 2021 · 4 comments
Closed

性能疑问 #214

lijialiang opened this issue Dec 6, 2021 · 4 comments

Comments

@lijialiang
Copy link

lijialiang commented Dec 6, 2021

在本地测试 Small input 中 javascript 性能比 napi 高效

napi @ Small input x 1,431,991 ops/sec ±0.91% (84 runs sampled)
napi#buff @ Small input x 1,535,086 ops/sec ±0.50% (92 runs sampled)
napi#asyncBuff @ Small input x 102,749 ops/sec ±0.46% (82 runs sampled)
javascript @ Small input x 2,553,005 ops/sec ±0.10% (99 runs sampled)
Small input bench suite: Fastest is javascript @ Small input
@lijialiang
Copy link
Author

原因来自于注释了

#[global_allocator]
static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc;

重新测试后的结果如下

napi @ Small input x 2,459,825 ops/sec ±0.38% (89 runs sampled)
napi#buff @ Small input x 2,947,302 ops/sec ±0.15% (93 runs sampled)
napi#asyncBuff @ Small input x 108,739 ops/sec ±0.49% (83 runs sampled)
javascript @ Small input x 2,554,025 ops/sec ±0.13% (99 runs sampled)
Small input bench suite: Fastest is napi#buff @ Small input

@Brooooooklyn
Copy link
Member

allocator 会极大程度的影响对内存频繁申请释放的程序性能

@lijialiang
Copy link
Author

对于我另外一个案例似乎不起作用,且目前性能差异相距甚大,请教一下可以有哪些具体的优化方向?(例如:simd)

正则转换 html 内容类似 <div>{{ data }}</div> 编译为 <div>hello</div>

js

exports.compileHtmlStr = (html, data) => {
  const reg = new RegExp(/{{\s*data\s*}}/g)
  return html.replace(reg, data)
}

napi + rust

#[macro_use]
extern crate napi_derive;

use regex::Regex;
use napi::{JsObject, JsString, Result, CallContext};

#[global_allocator]
static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc;

#[module_exports]
fn init(mut exports: JsObject) -> Result<()> {
  exports.create_named_method("compileHtmlStr", compile_html_str)?;
  Ok(())
}

#[js_function(2)]
fn compile_html_str(ctx: CallContext) -> Result<JsString> {
  let html = ctx.get::<JsString>(0)?.into_utf8()?;
  let data = ctx.get::<JsString>(1)?.into_utf8()?;
  let reg = Regex::new(r"\{\{\s*data\s*\}\}").unwrap();
  let c_html = reg.replace_all(html.as_str()?, data.as_str()?);
  ctx.env.create_string_from_std(c_html.to_string())
}

测试 bench 结果

CompileHtmlStr#Node x 5,543,011 ops/sec ±1.16% (88 runs sampled)
CompileHtmlStr#Rust x 43,318 ops/sec ±0.47% (95 runs sampled)
Fastest is CompileHtmlStr#Node

@Brooooooklyn
Copy link
Member

regex 这个包的 SIMD 加速效果不如 escape 这个场景这么明显,无法抵消 Node-API call overhead 的消耗

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants