As someone living (and coding) in a time reliant on technology and the internet, surely, you’ve also become dependent on performance speed. How many times have we all gotten frustrated and refreshed because 5 seconds of waiting felt like FAR too long? 5 SECONDS!
An Intro to Garbage Collection
- Allocate the memory needed (i.e. create a variable)
- Use the allocated memory (i.e. pass that variable as an argument)
- Release the memory when no longer needed
A very primitive example of garbage collection would be if we declare a variable to be used at the beginning of our program and overwrite it later in the code. In terms of memory, that original declaration of the variable is no longer “reachable”, so our garbage collector will trash it, or release that memory space. Garbage collection can, of course, get much more complex (and we won’t get into that) but, for our purposes, just know that it’s being performed automatically to free up memory while your program is running.
Great, but what can I do?
- You’re a developer — use the developer tools! Chrome (my browser of choice) has some pretty cool things built in for us to work with. Check out the Memory tab in your browser dev tools, next time you run an application. Choose the snapshot option to see what pieces of your code are taking up the most time when running your program. If any percentage is super high, you’ll know that’s a good place to revisit.
4. Single responsibility saves speed: One of the earliest code principles I learned at Flatiron was that if your method/function is doing more than one thing, it’s doing too much. If your function/loop/array is only performing one (or very few) actions, it can be completed and garbage collected much faster, than if it has to go through several steps.
5. Meh, let’s minify: Can’t be bothered with refactoring but have suuuuper long .js files and a lot of them? You can always minify. Fair warning — this makes code MUCH harder to read, so it isn’t necessarily recommended. It will remove all of the white space within your code, so while it’s not reader-friendly, it’s much quicker for your browser to parse. A simple Google search will return several minifying options.
Low-level languages like C, have manual memory management primitives such as malloc() and free(). In contrast…developer.mozilla.org