Skip to content

Commit 440aa63

Browse files
chore: potential optimisations
1 parent 3fdb3f0 commit 440aa63

File tree

2 files changed

+15
-9
lines changed

2 files changed

+15
-9
lines changed

cpp/msgpack.hpp

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@
55
#include <vector>
66
#include <jsi/jsi.h>
77
#include "cmp.h"
8-
#include <iostream>
9-
#include <sstream>
108

119
using namespace facebook;
1210

@@ -99,11 +97,18 @@ static bool mp_reader(cmp_ctx_t *ctx, void *data, size_t limit)
9997

10098
struct MessagePackWriter
10199
{
102-
std::stringstream stream;
100+
std::vector<uint8_t> data;
101+
102+
MessagePackWriter()
103+
{
104+
data.reserve(1024);
105+
}
103106

104107
size_t write(void *data, size_t count)
105108
{
106-
stream.write(static_cast<const char *>(data), count);
109+
size_t prev_size = this->data.size();
110+
this->data.resize(prev_size + count);
111+
std::move(static_cast<const uint8_t *>(data), static_cast<const uint8_t *>(data) + count, this->data.data() + prev_size);
107112
return count;
108113
}
109114
};
@@ -114,14 +119,14 @@ static size_t mp_writer(cmp_ctx_t *ctx, const void *data, size_t count)
114119
return mp->write(const_cast<void *>(data), count);
115120
}
116121

117-
std::vector<uint8_t> write(jsi::Runtime &rt, const jsi::Value &value)
122+
void write(jsi::Runtime &rt, const jsi::Value &value, std::vector<uint8_t> &data)
118123
{
119124
MessagePackWriter writer;
120125
std::unique_ptr<cmp_ctx_s> ctx(new cmp_ctx_s);
121126
cmp_init(ctx.get(), &writer, mp_reader, NULL, mp_writer);
122127
writeValue(ctx.get(), rt, value);
123-
const std::string &data = writer.stream.str();
124-
return std::vector<uint8_t>(data.begin(), data.end());
128+
writer.data.shrink_to_fit();
129+
data.swap(writer.data);
125130
}
126131

127132
jsi::Value readValue(cmp_ctx_t *ctx, jsi::Runtime &rt)

cpp/react-native-msgpack.hpp

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,16 @@ void install(jsi::Runtime &rt)
1212
const jsi::Value *args,
1313
size_t count) -> jsi::Value
1414
{
15-
auto data = write(rt, std::move(args[0]));
15+
std::vector<uint8_t> data;
16+
write(rt, args[0], data);
1617
auto size = data.size();
1718
jsi::ArrayBuffer arrayBuffer =
1819
rt.global()
1920
.getPropertyAsFunction(rt, "ArrayBuffer")
2021
.callAsConstructor(rt, static_cast<int>(size))
2122
.asObject(rt)
2223
.getArrayBuffer(rt);
23-
std::memcpy(arrayBuffer.data(rt), data.data(), size);
24+
std::memcpy(arrayBuffer.data(rt), std::move(data).data(), size);
2425
auto typedArray = rt.global()
2526
.getPropertyAsFunction(rt, "Uint8Array")
2627
.callAsConstructor(rt, std::move(arrayBuffer))

0 commit comments

Comments
 (0)