electron/shell/common/gin_helper/error_thrower.cc
trop[bot] 01ce103ae1
perf: have ErrorThrower lazily lookup the current isolate (#46415)
perf: have ErrorThrower lazy-lookup the current isolate

ErrorThrower's default constructor is marked as "should rarely if ever
be used" because it's expensive to call.

Unfortunately, nearly every instance of ErrorThrower comes as an argument
in gin_helper's JS-->C++ function marshalling where a thrower is
default-constructed and then populated in gin_helper::GetNextArgument()
with an assignment operator to a temporary ErrorThrower constructed
with the gin::Arguments' isolate.

tldr: most of the time we use the slow constructor first, then throw
that work away unused by overwriting with a fast-constructed one.

This refactor avoids that cost by deferring the expensive work to
`ErrorThrower::isolate()`, where it happens only as a fallback iff
isolate_ hasn't been set.

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Charles Kerr <charles@charleskerr.com>
2025-04-01 17:25:29 -05:00

47 lines
1.4 KiB
C++

// Copyright (c) 2019 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include <string_view>
#include "shell/common/gin_helper/error_thrower.h"
#include "gin/converter.h"
namespace gin_helper {
v8::Isolate* ErrorThrower::isolate() const {
// Callers should prefer to specify the isolate in the constructor,
// since GetCurrent() uses atomic loads and is thus a bit costly to invoke
return isolate_ ? isolate_.get() : v8::Isolate::GetCurrent();
}
void ErrorThrower::ThrowError(const std::string_view err_msg) const {
Throw(v8::Exception::Error, err_msg);
}
void ErrorThrower::ThrowTypeError(const std::string_view err_msg) const {
Throw(v8::Exception::TypeError, err_msg);
}
void ErrorThrower::ThrowRangeError(const std::string_view err_msg) const {
Throw(v8::Exception::RangeError, err_msg);
}
void ErrorThrower::ThrowReferenceError(const std::string_view err_msg) const {
Throw(v8::Exception::ReferenceError, err_msg);
}
void ErrorThrower::ThrowSyntaxError(const std::string_view err_msg) const {
Throw(v8::Exception::SyntaxError, err_msg);
}
void ErrorThrower::Throw(ErrorGenerator gen,
const std::string_view err_msg) const {
v8::Isolate* isolate = this->isolate();
if (!isolate->IsExecutionTerminating())
isolate->ThrowException(gen(gin::StringToV8(isolate, err_msg), {}));
}
} // namespace gin_helper