Skip to content

Commit d38b2ae

Browse files
committed
Optimise field access
1 parent 074cedf commit d38b2ae

3 files changed

Lines changed: 6 additions & 7 deletions

File tree

src/gc.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,8 @@ void GC::gc() {
119119
case ObjType::INSTANCE: {
120120
auto p = static_cast<ObjInstance*>(objptr);
121121
mark_as_grey(p->klass);
122-
for (const auto& [_, value] : p->fields.map) {
122+
for (const auto& [fieldname, value] : p->fields) {
123+
mark_as_grey(fieldname);
123124
mark_as_grey(value);
124125
}
125126
}

src/value.hpp

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -146,9 +146,7 @@ class ObjClass : public Obj {
146146
class ObjInstance : public Obj {
147147
public:
148148
ObjClass* klass;
149-
// TODO: we could use std::unordered_map<ObjString*, Value> here to avoid
150-
// creating the same string multiple times across different instances?
151-
StringMap<Value> fields;
149+
std::unordered_map<ObjString*, Value> fields;
152150

153151
ObjInstance(ObjClass* klass) : Obj(ObjType::INSTANCE), klass(klass) {}
154152

src/vm.cpp

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -461,8 +461,8 @@ InterpretResult VM::run() {
461461
}
462462
auto instanceptr = static_cast<ObjInstance*>(objptr);
463463
ObjString* property_name = read_constant_string();
464-
auto it = instanceptr->fields.map.find(property_name);
465-
if (it == instanceptr->fields.map.end()) {
464+
auto it = instanceptr->fields.find(property_name);
465+
if (it == instanceptr->fields.end()) {
466466
throw std::runtime_error("undefined property '" +
467467
property_name->value + "'");
468468
} else {
@@ -487,7 +487,7 @@ InterpretResult VM::run() {
487487
ObjString* property_name = read_constant_string();
488488
// NOTE: operator[] does not allow for heterogeneous lookup, so we need
489489
// to actually access the underlying std::string
490-
instanceptr->fields.map[property_name->value] = value_to_set;
490+
instanceptr->fields[property_name] = value_to_set;
491491
// Pop the instance and value, but leave the value on the stack since
492492
// (a.x = b) evaluates to b
493493
stack_pop();

0 commit comments

Comments
 (0)