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

faster conversion to slice #39

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

faster conversion to slice #39

wants to merge 1 commit into from

Conversation

ronag
Copy link
Contributor

@ronag ronag commented May 1, 2022

No description provided.

}

std::unique_ptr<char[]> heap_;
std::array<char, 1024> stack_;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks like an optimization for an overly-specific use case.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Most keys are < 1024 in length...

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's probably a fair assumption, but doesn't it then over-allocate memory?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's stack allocated?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe 1024 is a bit high considering cache locality...

Copy link
Contributor Author

@ronag ronag left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I went with this in the end:

struct NapiSlice : public rocksdb::Slice {
  std::unique_ptr<char[]> heap_;
  std::array<char, 128> stack_;
};

napi_status ToNapiSlice(napi_env env, napi_value from, NapiSlice& slice) {
  if (IsString(env, from)) {
    NAPI_STATUS_RETURN(napi_get_value_string_utf8(env, from, nullptr, 0, &slice.size_));
    char* data;
    if (slice.size_ + 1 < slice.stack_.size()) {
      data = slice.stack_.data();
    } else {
      slice.heap_.reset(new char[slice.size_ + 1]);
      data = slice.heap_.get();
    }
    data[slice.size_] = 0;
    NAPI_STATUS_RETURN(napi_get_value_string_utf8(env, from, data, slice.size_ + 1, &slice.size_));
    slice.data_ = data;
  } else if (IsBuffer(env, from)) {
    void* data;
    NAPI_STATUS_RETURN(napi_get_buffer_info(env, from, &data, &slice.size_));
    slice.data_ = static_cast<char*>(data);
  }
  return napi_ok;
}

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

Successfully merging this pull request may close these issues.

2 participants