Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Dumb Lowtax posted:

Wow, are those jsperf measurements for real? That difference is severe. I thought for sure JS engine would just optimize most cases to do the same thing as a for loop since in a lot of cases the programmer is just going to blindly use whichever syntax is their preference at the moment.

So it seems like most people's uses of for( x of y ) and forEach() out there would just be done upon plain old arrays in the most mundane way possible, yet the engine always assumes you might have some special type of list with an overridden custom iterator and runs it the really slow way just to be careful? Is that what's going on?

Does this mean if I go back in all my inner loops and turn all for( x of y ) and forEach() calls (where I was just trying to save an unnecessary counter variable) into for loops instead, I could have as big of speed gains as those graphs show?

Maybe! Try it on your codebase and profile it. Is most of your time being spent in hot loops? In my codebase, it is, and it provided me a giant speedup. If your codebase is a random trash React app, probably not.

Rule 1 of compilers: the compiler is smarter than you
Rule 2 of compilers: the compiler is bound by some random specification weirdness bullshit to not be smarter than you
Rule 3 of compilers: the compiler is actually a lot stupider than you think
Rule 4 of compilers: both the compiler and I are very stupid as I spent too much time optimizing and not profiling my app

I still use for...of in not hot loops, because I like the syntax of the new loop, and honestly forEach is fast enough for my purposes.

Adbot
ADBOT LOVES YOU

huhu
Feb 24, 2006
What are the goto best ways for importing/exporting files in JS/React? My old job used to do a structure like
code:
components/
  Foo/
    Foo.js
    Foo.spec.js
    package.json
Where the package.json was
code:
{
  "name": "Foo",
  "main": "Foo.js"
}
However, I've never really liked the package.json and then imports end up like:
code:
import Foo from ../../components/Foo
I just started doing:
code:
components/
  Foo/
    Foo.js
    Foo.spec.js
  Bar/
    Bar.js
    Bar.spec.js
  index.js
Where index.js is:
code:
import Foo from './Foo/Foo'
import Bar from './Bar/Bar'

export {
  Foo,
  Bar
}
Where now imports are like:
code:
import { Foo, Bar } from '../components'
Which I like more. Curious what you guys think.

geeves
Sep 16, 2004

huhu posted:

Where index.js is:
code:
import Foo from './Foo/Foo'
import Bar from './Bar/Bar'

export {
  Foo,
  Bar
}
Where now imports are like:
code:
import { Foo, Bar } from '../components'
Which I like more. Curious what you guys think.

I do this. It's a bit of overhead, but worth it and I usually add this with Babel / Webpack resolve and
code:
import {Foo} from "Components"

Suspicious Dish posted:

I still use for...of in not hot loops, because I like the syntax of the new loop, and honestly forEach is fast enough for my purposes.

I wish they had given us something more like
code:
for (const value : myArray)

MrMoo
Sep 14, 2000

geeves posted:

When I say forEach, I guess I should have clarified all of the array methods including map, reduce and filter. Usually if I'm using forEach I just use a regular loop given performance https://jsperf.com/fast-array-foreach

More variability here : https://jsperf.com/for-vs-foreach/293

geeves
Sep 16, 2004


The plot thickens. But that's the only one not to call add()

code:
(function() {
  var sum = 0;
  values.forEach(function(val) {
    sum += val;
  });
})();

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



geeves posted:

The plot thickens. But that's the only one not to call add()

code:
(function() {
  var sum = 0;
  values.forEach(function(val) {
    sum += val;
  });
})();

The one you posted was a bad comparison because they wrapped the callback in another function and I can't be bothered to sift through hundreds of revisions to find one where they didn't.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Compilers are complicated and microbenchmarks are generally useless. forEach being faster than a for loop in one test does not mean it is faster in all cases, since compilers can inline the callback in specific cases.

In old versions of V8, for instance, it used a "compilation complexity" heuristic that was byte size of the function, so simply adding comments and whitespace could kill an inline.

Profile your app and make decisions based on what's there.

MrMoo
Sep 14, 2000

It's a bit odd as they don't include Array.reduce() which they are reimplementing.

FSMC
Apr 27, 2003
I love to live this lie
I think I started the loop discussion and my code when full circle.
code:
//from
for(var i=0;i<a.length... 
//to
forEach... 
//to 
for(element in a... 
//then back to
for(var i=0;i<a.length... 
Now a follow on. I need some debugging advice. I've got some js which works perfectly in chrome, opera, and ie11. But it also needs to run in ie11 with some corporate ie8 emulator mode. Now with the ie11 dev tools open it works fine, but stops working when I close the dev tools. How do I work out what is going on since as soon as I try and look at source, and element, the console, etc. it start to work. I've remove all traces of console.log but I'm not sure if there is anything else that makes debug mode work different than normal.

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

FSMC posted:

I think I started the loop discussion and my code when full circle.
code:
//from
for(var i=0;i<a.length... 
//to
forEach... 
//to 
for(element in a... 
//then back to
for(var i=0;i<a.length... 
Now a follow on. I need some debugging advice. I've got some js which works perfectly in chrome, opera, and ie11. But it also needs to run in ie11 with some corporate ie8 emulator mode. Now with the ie11 dev tools open it works fine, but stops working when I close the dev tools. How do I work out what is going on since as soon as I try and look at source, and element, the console, etc. it start to work. I've remove all traces of console.log but I'm not sure if there is anything else that makes debug mode work different than normal.

First, be extra sure you got rid of all the console.logs, because unless the console is open, accessing the console will throw an exception and it'll skip over all the code (you do realize that the IE11 debugger has traces and you can just log stuff to console by right clicking in the debugger and adding a tracepoint right?)

Second, did you try setting the debugger's exception catching mode to 'break on all exceptions?'

Third, you can open the debugger using the 'debugger' statement in js, so one possibility is putting that statement in the place that doesn't get called when debugger is closed, and moving that statement earlier and earlier in the program until the debugger starts opening, and then concluding that such-and-such line is the culprit. There are some exceptions that are handled differently when debugger is open/closed - an example time this bit me was in the IE10 days with 'use strict' - my js had 'use strict', and if your code has 'use strict', and there's a strict mode violation, in IE10, the code would not throw an exception or open the debugger, it would just do gently caress all, but it would work if the debugger is open! (Hmm, sounds like your problem come think of it)

Roadie
Jun 30, 2013

FSMC posted:

I think I started the loop discussion and my code when full circle.
code:
//from
for(var i=0;i<a.length... 
//to
forEach... 
//to 
for(element in a... 
//then back to
for(var i=0;i<a.length... 

There is no excuse for ever using the i++ style loop unless you're very specifically doing something with the index value that's impossible to do with any of the other styles.

Happy Thread
Jul 10, 2005

by Fluffdaddy
Plaster Town Cop

Roadie posted:

There is no excuse for ever using the i++ style loop unless you're very specifically doing something with the index value that's impossible to do with any of the other styles.

After seeing those performance tests on the previous page I'm going to try it anyway in my inner loops and run the profiler just to be sure whatever else I typed was being inlined to that same thing basically by the compiler

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

Dumb Lowtax posted:

After seeing those performance tests on the previous page I'm going to try it anyway in my inner loops and run the profiler just to be sure whatever else I typed was being inlined to that same thing basically by the compiler

At least one problem with flying by performance numbers is the McNamara fallacy, e.g.

quote:

The first step is to measure whatever can be easily measured. This is OK as far as it goes. The second step is to disregard that which can't be easily measured or to give it an arbitrary quantitative value. This is artificial and misleading. The third step is to presume that what can't be measured easily really isn't important. This is blindness. The fourth step is to say that what can't be easily measured really doesn't exist. This is suicide.
.

There's a tendency when that quantitative facts (e.g. for loops written with 'i' are x amount faster) are juxtaposed with qualitative facts (foreach and for in loops are easier to maintain) to allow the more measurable thing to win. It can feel safer to rely on quantitative facts than qualitative facts (which can often be reduced to the level of anecdote). So let me throw down some anecdotes:

a) The difference in your type of for loop is trivial in almost all for loops given data size and expected iterations.
b) In places where the type of for loop actually makes a difference, you probably have a larger design issue at work that would be better addressed than optimizing your for loop.
c) Scale matters - sure you might save 15ms by changing the loop type, but if the inner guts of the loop are taking 1 second in that time, who gives a gently caress about the iterator.

Now as a programmer, there's a natural inclination to believe the micro benchmarks, but do be aware that kind of thinking is what kept the vietnam war going for 7 years.

Kobayashi
Aug 13, 2004

by Nyc_Tattoo
Also lol at loop optimization when the rest of the page is larded up with 5 Mb worth of tracking and ad serving scripts.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
To be specific, my issue was that the new style of for...of loops allocated garbage which would mean that a GC pause would happen more quickly. I spent a long time optimizing for garbage every frame to the point where the for...of loop mattered for me.

I also have a *lot* of for loops in my app, every frame. I still have for...of loops for initial load and setup because I do not care about garbage everywhere, I just want to prevent garbage in the hot path frame loop.

I found this out because the browser's Performance Tools suggested that GC pause was where my framedrops were coming from, and the Allocations tab suggested the browser's builtin ArrayIterator.prototype.next() as a large culprit, along with several other places I was generating garbage.

I did not blindly obey advice from a random website's microbenchmark. Even *just* optimizing the Array away would not have improved performance in my case, because GC pauses only stop if you remove all the places you generate garbage.

FSMC
Apr 27, 2003
I love to live this lie

Roadie posted:

There is no excuse for ever using the i++ style loop unless you're very specifically doing something with the index value that's impossible to do with any of the other styles.


Well. I had some issues with some scripts not recognising forEach, and also needing ie8 support meant I remove foreach. I tried for(var x in y), but the behaviour is strange. I expect x to be the value, but sometimes it's an index. So I binned that and went back to i++.

qsvui
Aug 23, 2003
some crazy thing

FSMC posted:

Well. I had some issues with some scripts not recognising forEach, and also needing ie8 support meant I remove foreach. I tried for(var x in y), but the behaviour is strange. I expect x to be the value, but sometimes it's an index. So I binned that and went back to i++.

I haven't had that much experience with JS, but shouldn't for-in loops always yield the index because they return the keys not the values? The for..of loops that people have been talking about should be the one you want if you need values (granted that they would probably not work in IE).

qsvui fucked around with this message at 15:07 on Jul 23, 2018

FSMC
Apr 27, 2003
I love to live this lie

qsvui posted:

I haven't had that much experience with JS, but shouldn't for-in loops always yield the index because they return the keys not the values? The for..of loops that people have been talking about should the one you want if you need values (granted that they would probably not work in IE).

Thanks. I didn't realise there was a difference. That explains why I thought the behaviour was inconsistent, when in fact I was just using in/of inconsistently.

Happy Thread
Jul 10, 2005

by Fluffdaddy
Plaster Town Cop

FSMC posted:

Thanks. I didn't realise there was a difference. That explains why I thought the behaviour was inconsistent, when in fact I was just using in/of inconsistently.

About one out of every ten times I'll still accidentally type "in" rather than "of" for an array iterator and wonder why it doesn't work

Roadie posted:

There is no excuse for ever using the i++ style loop unless you're very specifically doing something with the index value that's impossible to do with any of the other styles.

If you're new to these iterators, remember that you can still get the index with a for...of loop, if you do happen to need the counter for some math, without sacrificing the automatic setting of how many loop iterations so you don't have to type the array size.

Just do
code:
for( let [i,x] of your_array.entries() )
Or for an object, do either a for...in loop or do
code:
for( let [i,x] of Object.entries( your_object ) )
.

Kobayashi posted:

Also lol at loop optimization when the rest of the page is larded up with 5 Mb worth of tracking and ad serving scripts.

I went library free so no bloat here. In my case my JavaScript makes WebGL calls, so moving computationally hard tasks off of the client is not an option... graphics programs are often inherently going to have some performance heavy stuff. Often I make inner loops are about testing ray-volume intersections and volume-volume intersections and these naturally take much longer than the rest of the program.

Right now my approach in the ray-volume testing function is to just use Array iterator methods (map, reduce, forEach) on my math vectors, which themselves are hidden behind class methods with better math names like "add" and "times" and "dot". This is super readable and maintainable. But maybe for just this one function, my compromise could be to have two versions of it: A "readable" version and an equivalent "fast" version with all loops completely unrolled. Maybe I never call the readable one at all and it's just there for reference.

Roadie
Jun 30, 2013

FSMC posted:

Well. I had some issues with some scripts not recognising forEach, and also needing ie8 support meant I remove foreach.

Use babel, babel-preset-env with useBuiltIns: true, babel-polyfill, and a .browserslistrc with your target browsers. Then you'll never have to give a crap about browser-specific functionality again.

Edit: Except fetch, because for whatever insane reason corejs doesn't care enough to use isomorphic-fetch or even a "only if window exists" check with whatwg-fetch.

Roadie fucked around with this message at 23:53 on Jul 22, 2018

FSMC
Apr 27, 2003
I love to live this lie

Roadie posted:

Use babel, babel-preset-env with useBuiltIns: true, babel-polyfill, and a .browserslistrc with your target browsers. Then you'll never have to give a crap about browser-specific functionality again.

Edit: Except fetch, because for whatever insane reason corejs doesn't care enough to use isomorphic-fetch or even a "only if window exists" check with whatwg-fetch.

Ahhhh!!!!!. Babel looks perfect. How comes I can never find anything useful on JS with google. I can never find details of how functions work, details of looks, the different types of for loops, etc. I spent a good half an hour searching for something like babel without any success.

Happy Thread
Jul 10, 2005

by Fluffdaddy
Plaster Town Cop
Just keep trying with Google, specifically the results where people have posted code on stackoverflow to answer the question. I've found out about so many clever ways to write JS concepts from those posts that permanently changed how I did things going forward. If you see from regularly reading clever answers how many of the newer language features can be not only used but repurposed you'll learn to write code that is not just less complex to read but manages to introduce *more* functionality or features than you planned on.

necrotic
Aug 2, 2005
I owe my brother big time for this!

FSMC posted:

Ahhhh!!!!!. Babel looks perfect. How comes I can never find anything useful on JS with google. I can never find details of how functions work, details of looks, the different types of for loops, etc. I spent a good half an hour searching for something like babel without any success.


MDN is probably the best technical resource for javascript right now. It wouldn't have helped you find babel, but it has details on all the standard functions and looping styles.

https://developer.mozilla.org/en-US/

Roadie
Jun 30, 2013
Aggressively-maintained megacorporate projects like create-react-app are a pretty good indicator of what's considered "state of the art" with JS stuff right now.

Also, make sure to keep up with the basic terminology being used. Like, Babel is on the front page of a search for "js transpiler" using WHICHEVER_SEARCH_ENGINE.

Roadie fucked around with this message at 05:17 on Jul 23, 2018

reversefungi
Nov 27, 2003

Master of the high hat!
For you folks using VS Code + React, any particular extensions you guys have found that have been really useful?

Dr. Poz
Sep 8, 2003

Dr. Poz just diagnosed you with a serious case of being a pussy. Now get back out there and hit them till you can't remember your kid's name.

Pillbug

huhu posted:

Where index.js is:
code:
import Foo from './Foo/Foo'
import Bar from './Bar/Bar'

export {
  Foo,
  Bar
}

Agreed, and there is an alternate syntax well:

code:
export { default as Foo } from './Foo/Foo'
export { default as Bar } from './Bar/Bar'

Video Nasty
Jun 17, 2003

FSMC posted:

Ahhhh!!!!!. Babel looks perfect. How comes I can never find anything useful on JS with google. I can never find details of how functions work, details of looks, the different types of for loops, etc. I spent a good half an hour searching for something like babel without any success.

Devdocs.io is invaluable as a reference for languages and has examples of usage for darn near everything. Also works offline.

Odette
Mar 19, 2011

Video Nasty posted:

Devdocs.io is invaluable as a reference for languages and has examples of usage for darn near everything. Also works offline.

There's also Zeal Docs for Linux & Windows. It's basically a clone of Dash for OSX.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

I always wonder what kind of workflow a developer (other than devs working offline) has that makes tools like that useful.

For me, 100% of the time, a quick Google always takes me to the most relevant docs page...much more quickly than perusing the docs directly.

necrotic
Aug 2, 2005
I owe my brother big time for this!
On OSX I use Alfred with Dash integration, so a quick hotkey lets me search docs for all the languages I have picked. If I don't know what I'm looking for then yeah, Google is the target.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Thermopyle posted:

I always wonder what kind of workflow a developer (other than devs working offline) has that makes tools like that useful.

For me, 100% of the time, a quick Google always takes me to the most relevant docs page...much more quickly than perusing the docs directly.

I bet it's nice if you travel a lot and want to try to get some work done on the plane or train or whatever

Odette
Mar 19, 2011

Munkeymon posted:

I bet it's nice if you travel a lot and want to try to get some work done on the plane or train or whatever

Bingo. I use it extensively when I'm on planes.

EDIT: Plus there's way too many places with lovely wifi, like hotels.

Chenghiz
Feb 14, 2007

WHITE WHALE
HOLY GRAIL

Thermopyle posted:

I always wonder what kind of workflow a developer (other than devs working offline) has that makes tools like that useful.

For me, 100% of the time, a quick Google always takes me to the most relevant docs page...much more quickly than perusing the docs directly.

It's nice when Github is down.

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!
I'm trying to get my head around the behavior of node_modules (with typescript).

It seems like the standard way of installing your module dependencies is "npm install whatever" in your project path, which makes a node_modules folder, which seems like ... a heap of crap. I don't want all the dependencies of a project in the same path as that project. But it seems that "npm install -g whatever" to install things in the global space doesn't make them available for imports?

What's the non-stupid way of doing this? I must be missing something. People do this with git, and surely don't have all their dependencies in their git repositories - do they just put node_modules in their .gitignore? If so, are the dependencies captured somewhere else so there's a record of what your module needs somewhere? Or are you supposed to set it up so you do npm install somewhere *above* your project path?

Everything I find saying how to do things just seems to manually mash the node_modules dependencies right into the middle of your project, surely that can't really be the way?

fantastic in plastic
Jun 15, 2007

The Socialist Workers Party's newspaper proved to be a tough sell to downtown businessmen.

roomforthetuna posted:

What's the non-stupid way of doing this? I must be missing something. People do this with git, and surely don't have all their dependencies in their git repositories - do they just put node_modules in their .gitignore? If so, are the dependencies captured somewhere else so there's a record of what your module needs somewhere? Or are you supposed to set it up so you do npm install somewhere *above* your project path?

Everything I find saying how to do things just seems to manually mash the node_modules dependencies right into the middle of your project, surely that can't really be the way?

Yes, people put node_modules in their .gitignore. The dependencies should be captured in a file called package.json, which is kept in the root of the repo. If you have this file, and you run "npm install", npm will go fetch and install all of the dependencies.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

roomforthetuna posted:

I'm trying to get my head around the behavior of node_modules (with typescript).

It seems like the standard way of installing your module dependencies is "npm install whatever" in your project path, which makes a node_modules folder, which seems like ... a heap of crap. I don't want all the dependencies of a project in the same path as that project. But it seems that "npm install -g whatever" to install things in the global space doesn't make them available for imports?

What's the non-stupid way of doing this? I must be missing something. People do this with git, and surely don't have all their dependencies in their git repositories - do they just put node_modules in their .gitignore? If so, are the dependencies captured somewhere else so there's a record of what your module needs somewhere? Or are you supposed to set it up so you do npm install somewhere *above* your project path?

Everything I find saying how to do things just seems to manually mash the node_modules dependencies right into the middle of your project, surely that can't really be the way?

You put node_modules in your .gitignore. All your dependencies are listed in your package.json file, which you include in your repo. Problem solved.

e:f;b :argh:

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
When you run npm install, pass --save as an argument. This will add it to the package.json and package-lock.json files allowing others to simply install and be on their way.

Why this isn't a default is beyond me.

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!
Aha, thanks guys. So I was close to guessing right, it just seems weird, having the same module installed in multiple places if you work on multiple things. Oh well.
And thanks for the --save tip, that seems less irritating than having to do the install and modify the file manually. (Though as you say, does seem weird that it's not the default.)

Joda
Apr 24, 2010

When I'm off, I just like to really let go and have fun, y'know?

Fun Shoe
I put them in global and link to projects. Is that bad?

Adbot
ADBOT LOVES YOU

Doom Mathematic
Sep 2, 2008

Suspicious Dish posted:

Why this isn't a default is beyond me.

In recent versions of npm it is.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply