Fixed some low hanging fruit in performance.

This commit is contained in:
2020-10-09 12:55:49 +02:00
parent 43f080cc48
commit dcb6c58f90
6 changed files with 79 additions and 53 deletions

View File

@@ -6,42 +6,42 @@
#include <stdexcept>
namespace MalachScript::Utils {
template <size_t initialSize, size_t steps>
class MemoryPool {
template <size_t initialSize, size_t steps> class MemoryPool {
public:
MemoryPool() : _offset(0), _capacity(initialSize) {
auto *ptr = malloc(_capacity);
MemoryPool() {
auto* ptr = malloc(initialSize);
if (ptr == nullptr) {
throw std::logic_error("Out of memory.");
}
_memory = static_cast<uint8_t*>(ptr);
_head = static_cast<uint8_t*>(ptr);
_tail = _head;
_end = _head + initialSize;
}
~MemoryPool(){
free(_memory);
}
~MemoryPool() { free(_head); }
template <class T, class... parameters> T* Create(parameters... args){
if (_offset + sizeof(T) >= _capacity) {
template <class T, class... parameters> T* Create(parameters... args) {
auto* p = _tail + sizeof(T);
if (p >= _end) {
IncreaseStep();
}
auto* element = new (_memory + _offset) T(args...);
_offset += sizeof(T);
auto* element = new (_tail) T(args...);
_tail = p;
return element;
}
private:
size_t _offset;
size_t _capacity;
uint8_t* _memory = nullptr;
uint8_t* _tail = nullptr;
uint8_t* _end;
uint8_t* _head = nullptr;
void IncreaseStep(){
_capacity += steps;
auto newPtr = realloc(_memory, _capacity);
void IncreaseStep() {
_end += steps;
auto newPtr = realloc(_head, _end - _head);
if (newPtr == nullptr) {
throw std::logic_error("Out of memory.");
}
_memory = static_cast<uint8_t*>(newPtr);
_head = static_cast<uint8_t*>(newPtr);
}
};
}