Is the map function inefficient? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm learning a little bit of efficiency code.
I do the next code.
The map function returns a result slower.
https://i.stack.imgur.com/oVSBw.png
i'm doing something wrong?
var user = [
{
name: 'Sebastian',
age: 19
},
{
name: 'Gabriela',
age: 51
},
{
name: 'Julian',
age: 19
}
]
console.time('map');
user.map(item => console.log(item.name));
console.timeEnd('map');
console.log('\n');
console.time('for');
for (var i = 0; i < user.length; i++) {
console.log(user[i].name);
}
console.timeEnd('for');

Fundamentally, JavaScript is not a programming language where doing something in the cleanest way is also the most efficient way. C, D, and C++ are languages that are designed that way.
If you look into V8 internals, you'll notice that map has to deal with array holes, making it slower.

No it is not inefficient. You are comparing map with normal for. .map adds a layer of abstraction from the outside scope with results in an increase in the execution time when compared with the normal for.

Related

What's the performance difference between using Object.keys and lodash _.keys() [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Opinion-based Update the question so it can be answered with facts and citations by editing this post.
Improve this question
Is there any performance difference between using ES6 Object.keys and lodash _.keys()?
Or what is the benefit of using one against another?
Recently I am considering which one to use is best practice, does anyone knows what goes under the hoods of each? Thanks.
The library method _.keys is written in Javascript, not native code - when both native code and a custom function can accomplish X, native code is almost always faster, because it's built into the browser and written on a lower-level (like in C++):
const obj = [...new Array(50)];
const p0 = performance.now();
for (let i = 0; i < 1e5; i++) {
_.keys(obj);
}
const p1 = performance.now();
console.log('lodash', p1 - p0);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
const obj = [...new Array(50)];
const p0 = performance.now();
for (let i = 0; i < 1e5; i++) {
Object.keys(obj);
}
const p1 = performance.now();
console.log('Object.keys', p1 - p0);
That said, worrying about such optimizations is usually not important - often, if your script has a bottleneck, it'll very likely be somewhere else. Avoid premature optimization. If your current codebase uses _.keys and you don't repeatedly call _.keys huge numbers of times, it's probably not something to worry about - you might consider sticking with your codebase's current style, whichever it is, for now, unless / until you run into performance issues.
Another difference is that Object.keys is an ES5 method. If you have to support extraordinarily ancient browsers, they may not be able to use Object.keys without a polyfill (and a polyfill would likely have similar performance to the Lodash implementation).

Iterating over an array with `every` [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
The book that I'm studying says about iterating over arrays with every that:
The function these methods use must follow one ruleā€”it must accept
three arguments like the following code:
function functionName(value, index, array) {
// do something here
}
Does that mean that I must always use 3 arguments? If so then why does this code work?
var numbers = [ 1, 2, 2 ];
function isLessThan3(value) {
var returnValue = false;
if (value < 3) {
returnValue = true;
}
return returnValue; }
document.write(numbers.every(isLessThan3));
There is no limitation on how many arrguments you can put in a function with Javascript.
you have a very good explenation about this topic in the next answer by #Niet the Dark Absol
https://stackoverflow.com/a/22747272/1283672
i believe that the book was reffering to something more specific within it's scope.
And just to be clear you can put no arrgs in a function either.
It's a bit ugly, the code, you have, but there is help. You might use the following without a temporary variable. Just return the result of the comparison.
function allLessThan3(value) {
return value < 3;
}
var numbers = [1, 2, 2];
console.log(numbers.every(allLessThan3));
No, you can use from 0 to 3 arguments

Is using an Array.map as a foreach good practice? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I'm already using an Array.map, but with the same data, I need to do some other calculations. Should I do those calculations within the map or do it in a for each after the map?
return res.data.map(function (obj) {
if(obj.status.id == 6 || obj.status.id == 5){
dateDifference(obj.created_at,obj.closed_at);
}else{
$scope.open++;
}
return {
"id":obj.id,
"subject": obj.subject,
"requester": obj.requester.name,
"assigned": obj.assigned ? obj.assigned.name : '',
"priority": obj.priority.name,
"status": obj.status.name,
"category": obj.category.name,
"created_at": moment(obj.created_at).utcOffset("06:00").format('lll'),
"updated_at": moment(obj.updated_at).utcOffset("06:00").format('lll')
}
})
I don't see it as a 'good practice', but I don't see it as a bad practice either. Fact is, .map() is designed to both iterate and create a new resulting array.
Perhaps the answer lies in its definition.
From the JS website :
"The map() method creates a new array with the results of calling a
provided function on every element in this array."
From the PHP website (for fun) :
"array_map() returns an array containing all the elements of array1
after applying the callback function to each one."
Nothing keeps you from doing what you want in that callback function.
If you, personnally, are not comfortable doing that, you could achieve the same thing doing a 'for each' while building your own new array. Which is probably what I would do in your specific case. I'd rather do that than have to iterate 2 times over my array.
Though, as Bergi mentionned, it is a better practice to iterate twice over the array if it makes sense sematically.
If performance were to become an issue (iterating twice on a long array). Here is what I would be inclined to do :
for (var i=0; i<myArray.length; i++) {
doStuffA(myArray[i]);
doStuffB(myArray[i]);
}
which is quite clear semantically. Instead of iterating twice.
Of course, some pleople might (will probably) disagree with me.

Treating order of elements in arrays as order of input? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Is it good practice to use the order of elements in arrays as signifying an implicit order?
The question sounds kinda funny. I'm asking is this ok:
{
raceWinners: ['john', 'peter', 'paul']
}
John was first place, Peter was second, and Paul got third place. It's implied by the order.
Or would this be better practice:
{
raceWinners: [{
name: 'peter',
placement: 2
}, {
name: 'john',
placement: 1
}, {
name: 'paul',
placement: 3
}]
}
I see the value of the second example because everything is explicit to you.
While in the first example, you can really muck up things if you accidentally popped(), when you should have shifted().

Should I wrap my function in if clause or use the opposite if condition and return prematurely? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
If the title isn't clear enough, which is probably the case, here's what I mean :
Is it better to do this :
function example() {
if (condition) {
//The whole function code
}
}
or
function example() {
if (!condition) {
return;
}
//The whole function code
}
What is the cleanest way ?
Edit : I am not asking for your opinion. I'm wondering if there's any rule/convention/performance improvement.
I prefer the second way, "golden path" style.
Since I started to write all of my code like that I've found it to be a lot easier to read later. Perform checks in the order that makes sense, and return as soon as anything unexpected happens.
Wrapping code in a new block also adds indentation, which is kind of a waste of screen real-estate.

Categories