electron/shell/common/gin_helper/error_thrower.h
Charles Kerr 0492f0f745
perf: have ErrorThrower lazily lookup the current isolate (#46388)
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.
2025-04-01 12:25:27 -05:00

39 lines
1.2 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.
#ifndef ELECTRON_SHELL_COMMON_GIN_HELPER_ERROR_THROWER_H_
#define ELECTRON_SHELL_COMMON_GIN_HELPER_ERROR_THROWER_H_
#include <string_view>
#include "base/memory/raw_ptr.h"
#include "v8/include/v8-forward.h"
namespace gin_helper {
class ErrorThrower {
public:
constexpr explicit ErrorThrower(v8::Isolate* isolate) : isolate_{isolate} {}
constexpr ErrorThrower() = default;
~ErrorThrower() = default;
void ThrowError(std::string_view err_msg) const;
void ThrowTypeError(std::string_view err_msg) const;
void ThrowRangeError(std::string_view err_msg) const;
void ThrowReferenceError(std::string_view err_msg) const;
void ThrowSyntaxError(std::string_view err_msg) const;
v8::Isolate* isolate() const;
private:
using ErrorGenerator = v8::Local<v8::Value> (*)(v8::Local<v8::String> err_msg,
v8::Local<v8::Value> options);
void Throw(ErrorGenerator gen, std::string_view err_msg) const;
raw_ptr<v8::Isolate> isolate_ = {};
};
} // namespace gin_helper
#endif // ELECTRON_SHELL_COMMON_GIN_HELPER_ERROR_THROWER_H_