<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var model = {type: {test: "a"}, action: "show", first: "eval", second: "Function"};
var func = new Function("model", "return model.type");
eval('model.type')
func(model);
_.template('${type}')(model);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
eval | |
Function | |
lodash.template |
Test name | Executions per second |
---|---|
eval | 16919374.0 Ops/sec |
Function | 238235728.0 Ops/sec |
lodash.template | 121534.9 Ops/sec |
Let's dive into the benchmarking test on MeasureThat.net.
Overview
The test compares three ways to access a nested property in an object: eval()
, Function
constructor, and lodash.template()
(a part of the Lodash library). The test aims to determine which approach is the fastest.
What's being tested?
In the benchmarking script, we have two main variables:
model
: an object with a nested property type.test
func
: a function created using the Function
constructor that returns the value of model.type
The test creates three versions of this scenario:
eval('model.type')
: uses the built-in eval()
function to access the nested property.func(model)
: uses the custom-made func
function to access the nested property._template('${type}')(model)
: uses Lodash's template()
function with a template string to create an interpolated value, and then applies this value to model
.Options compared
The three options are compared in terms of execution speed.
func
that returns the value of model.type
.Pros and Cons
Here are some pros and cons for each approach:
eval()
and Lodash template, requires more codeLodash library
The Lodash library is a popular JavaScript utility library that provides a wide range of functions for various tasks, such as array manipulation, object manipulation, function currying, and more. In this case, the template()
function is used to create an interpolated value.
Other considerations
Alternatives
If you need to access nested properties in objects, consider the following alternatives:
model['type.test']
): a more modern and secure way to access nested properties.const { type: { test } } = model;
) for object destructuring, which can be faster than eval()
or Lodash template.${model.type.test}
): another modern and secure way to create interpolated strings.Keep in mind that the best approach depends on your specific use case and performance requirements.