Skip to content

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