const obj = {
a: 'a',
b: 'b',
c: 'c'
}
const proxy = new Proxy(obj, {
get(target, key, receiver) {
return Reflect.get(target, key, receiver)
}
})
function getAFromProxy() {
return proxy.a;
}
function getA() {
return obj.a;
}
function getAFromFunction() {
return getA()
}
const outerProxyGetFunction = new Proxy({}, {
get(target, key, receiver) {
return getAFromFunction()
}
})
const outerProxyProxy = new Proxy({}, {
get() {
return getAFromProxy()
}
})
function getOuterProxyGetFunction(){
return outerProxyGetFunction
}
function getOuterProxyProxyAccess(){
return outerProxyProxy
}
getAFromFunction()
getAFromProxy()
getOuterProxyGetFunction().a
getOuterProxyProxyAccess().a
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Get Function | |
Proxy access | |
Get function wrapped in proxy | |
Proxy wrapped in proxy |
Test name | Executions per second |
---|---|
Get Function | 3808593.5 Ops/sec |
Proxy access | 2245376.5 Ops/sec |
Get function wrapped in proxy | 3741139.5 Ops/sec |
Proxy wrapped in proxy | 2401995.0 Ops/sec |
Let's break down the provided JSON benchmark and explain what's being tested.
Benchmark Overview
The test compares three different approaches to accessing a value in an object: a built-in get()
function, a custom getter function, and a proxy (a runtime-created object that provides access to an underlying object).
Approaches Compared
get()
function: This is the most straightforward approach. It uses the get()
method of the Object prototype to retrieve the value associated with a given key.getAFromFunction()
) is created that simply calls another function (getA()
), which returns the desired value. The custom getter function wraps around the original getA()
function and adds an extra layer of indirection.outerProxyGetFunction
) that wraps a function (getOuterProxyGetFunction()
) that returns another function (getAFromProxy()
), which is used to access the value through the inner proxy.innerProxyProxy
) that simply returns the result of calling getAFromProxy()
.Pros and Cons
get()
function:Libraries and Syntax
None of the approaches rely on any external libraries. However, JavaScript provides a built-in Proxy
object that can be used to create proxies.
The custom getter function uses a simple function call chain to access the value. The proxy approach creates two separate proxies using the new Proxy()
constructor and configures their behavior using objects with get()
methods.
Other Considerations
When choosing an approach, consider the specific requirements of your use case:
get()
function or custom getter function might be a better choice.Alternatives
Other alternatives to accessing values in an object include:
However, these alternatives may not provide the same level of control and flexibility as the approaches compared in this benchmark.