r/AskComputerScience • • Aug 05 '20

What are the ways to make a program faster and "lighter"

During my high school years I have been taught how to write good looking code, sorting it and using indentations, using comments when necessary... But how do you optimize your code? ELI5?

41 Upvotes

17 comments sorted by

30

u/DrunkHacker Aug 05 '20

These are all good suggestions, but they're missing the most important: instrumentation.

I've seen too many people try to optimize without knowing the bottleneck. Maybe it's inefficient memory use, maybe it's server latency, maybe it's using an inefficient algorithm somewhere--but without proper instrumenting, you're just playing optimization roulette. So become familiar with whatever tools are most appropriate and figure out what's slow -- then focus on that.

Second, an old saying goes, "premature optimization is the root of all evil." This isn't license to write sloppy code or copy+paste everywhere, but a general guideline not to worry too much about smaller optimizations on the first draft.

8

u/ohaz Aug 05 '20

an old saying goes, "premature optimization is the root of all evil." This isn't license to write sloppy code or copy+paste everywhere, but a general guideline not to worry too much about smaller optimizations on the first draft.

Yes! I had been programming for a few years when I had some courses about writing my own compiler and also writing some compiler optimizations when this saying really hit me. The compiler is sooooo much better at most optimizations than us humans. Don't worry about it. Since then, whenever I want to optimize something, I think "optimize algorithms, not code". If you have an algorithm that's O(n^3) and can get it to O(n), do that! But don't try to optimize your written code. Write code to make it readable for humans. The Compiler will do the rest.

Then, run your code. A lot. Try to figure out where the bottlenecks are. If you find any, try to optimize the algorithms around the bottleneck more. Only if that won't fix the issue, THEN start to optimize the code.

50

u/roman_fyseek Aug 05 '20

Use efficient algorithms. Don't do work more than once. Weigh the trade-offs between keeping stuff in memory and keeping stuff in a database/file system, doing the work once and stashing it to save CPU or doing the work multiple times and never storing it to save memory. Learn to use your profiling tools.

Practice this for 30 years and you'll still be learning optimization tricks.

1

u/[deleted] Aug 06 '20

Also avoid throwing your own implementations unless you are sure that a) the bottleneck is in the implementation and not the algorithm, b) you can actually do a better work without spending weeks on something.

8

u/Bottled_Void Aug 05 '20

Just two simple points to consider by way of example.

When you're passing around data between routines, are you passing a copy of that data, or a pointer to a single instance. How many copies of the data have you got flying around, do you need to do it thr way you have?

And the more simple one is to look at loops. How many iterations are you doing? What is inside that loop, does it need to be there? Can you quit out of the loop early if you find what you're looking for, or if you run into some fault?

I've generally found simple understandable code is far more important than making every line efficient.

If you hit up on high usage in your routine, you can usually find the problem area using profiling and just fix the inefficient section. Which is one of the reasons having simple easy to understand code is important. It makes the rework much easier.

4

u/lookayoyo Aug 05 '20

A good way to start early on is to reduce package bloat. If you are installing a package to do a single thing, see if you can do it another way. That way you reduce the number of required packages to run.

1

u/JOyo246 Aug 05 '20

This is my favorite story of optimization. You can see here that the one lined statement using his formula would be much more optimal than a for loop. https://nrich.maths.org/2478

2

u/ZY0Ns Aug 05 '20

Great read! From all the replies I now understand now that it's all about finding the best algorythm to get the desired result. I love these problem solving stories

3

u/sammypwns Aug 05 '20

This is sort of a difficult question to answer nowadays because of compilers and out of order execution in hardware.

Basically, compilers and cpus look at multiple assembly or compiler specific instructions at a time and then find dependency graphs that can be computed in parallel.

There are things that can slow this down. If your code has lots of if statements or it frequently allocates memory with no clear pattern, it becomes much harder for the compiler or cpu to optimize the code. For instance, if you're in a loop that's checking if i < 1000, the computer doesn't need to wait to know if i < 1000 to start executing the code in the loop because 999 out of 1000 times you're going to execute the code in the loop, but if you're code is branching erratically, then the computer can't optimize that as well.

The other issue is memory allocation. If you know how much memory you're going to need for a calculation ahead of time, it's best to allocate the memory once because each time a program asks for memory, the operating system has to setup some for the program to use. This is usually easy for compilers because the size of structs and arrays are often known ahead of time, but in interpreted languages like python and javascript, it can take several executions to get an understanding of the memory requirements. If you have code that is constantly altering the properties of hashmaps or constantly appending to arrays without knowing the final size, the computer will have to constantly allocate new memory, often having to copy objects to new, larger blocks of memory. All this stuff destroys performance. It's even worse if you have garbage collected language like java, go, or any interpreted languages because garbage collection scales with the amount of allocated memory blocks.

None of this really matters when solving a problem for the first time. It's essentially impossible to know exactly how compiler and cpu optimizations will affect code, and it's often more important to write programs in clear, manageable chunks. It's also important is to learn how to use a profiler and how to generate test loads on your program. All profilers will at least tell you how long each function is taking to execute so you can see where your bottlenecks are, although they may not tell you why exactly. Optimizations really only matter when performance becomes an issue, and clean, modular code is easier to refactor when that happens.

2

u/TransientVoltage409 Aug 05 '20

On programming: A designer knows he has achieved perfection not when there is nothing left to add, but when there is nothing left to take away. --Antoine de Saint-Exupery

On optimization: The Story of Mel, a Real Programmer

2

u/morphilng Aug 05 '20

There’s a lot of good answers here but I’m not sure about a proper ELI5.

When you’re first learning to program, you’re executing some simple statements, printing some things, maybe performing some algebra, and it’s so straightforward that there’s pretty much only one way to do it and not too many things that could meaningfully impact it’s performance.

In the real world, computers are often used to solve really big problems, like what’s the next largest prime number. For these problems the computer may have a much more complicated set of instructions, or might perform one block of code thousands of times. The process of optimization would involve looking at the block of code that is executed thousands or millions times over the course of the program to see if there is any way to do the same thing but with fewer instructions, maybe mathematically or with a programming trick or something along those lines.

Suppose you are trying to find the largest prime number. One solution would be to look at each number and check if it is divisible by any number less than itself. This works, but once the numbers get really big, you’re checking tons of divisors and the program will start to take a super long time. However, the number of checks can be drastically reduced with some different approaches. For example, ruling out even numbers will eliminate half of the numbers to check. Similarly, only checking divisors that are less than half of the candidate number is mathematically sound and will reduce the number of divisor checks by half. Suddenly your program is performing 25% of the calculations to arrive at the same result, which makes a big difference when the problem takes several minutes for the computer to solve.

Mathematicians and computer scientists have been developing efficient ways to solve big problems for decades now. For large problems with scary compute times, being smart with your instructions makes quite a difference. Some problems are so algorithmically complex that they’re considered impossible to perfectly solve on a computer in an efficient way (google: NP-Hard problems).

2

u/[deleted] Aug 05 '20

Only print to console when you have to, or when it will legitimately help with development and production support moving forward. Writing to the screen causes an interrupt, so it will stall the code. This is only a minor thing, but if you're trying to run your code for real after a bunch of debugging, make sure you remove any "diagnostic" logging

2

u/josh2751 Aug 05 '20

Understand how your data structures work, and use the right ones in the right manner for your particular problem. Understand their time and memory complexity and how they implement them and why it matters.

That's a huge part of optimization right there, and you can do it in your head before you write a line of code. Also don't be afraid to go back and change a data structure if you find out you were wrong in your initial ideas.

2

u/kellyjj1919 Aug 05 '20

A lot of good answers here.

For myself, the first I do is get my code to work. Fast efficient code isn’t good if it doesn’t work.

Then, I go through trim the fat. Am I loading a file multiple times, even though I need it only once? Maybe running queries that pull the same data? A lot of times you are just trying get things working & do silly things. Sadly this clears up a lot bottle necks for me.

Then I start to look at my algorithms.

3

u/jcliberatol Aug 05 '20

Optimizing is very sexy and we all want to do it but always remember the priorities would be:

  1. Keep it readable and documented (not only comments but actual documentation)

  2. Optimize first for reading the code, then for writing it and debugging it.

Now for actual optimization:

  1. Use caches, everywhere that you can, for instance in webapps i usually use localStorage in order to see if a query i will do has already be done by this client and not do it again. Using caches also can mean using the processor cache so if you are doing hardcore c++ on matrices, access per row and not per column since the row has already been loaded in the deepest caches, and do operations in local batches of memory first, so if you have to do multiple operations over large matrices try to do them as locally as possible and not reading the whole matrix multiple times.

  2. Keep your memory tidy, so dont declare heaps and heaps of memory you will not be reusing, of course if you are using a variable a lot by all means keep it accessible. Good memory practices in your pointers or matrices arrays/etc will go a long way in making a program faster.

  3. Choose your libraries well, try to use swissknife kinda libraries instead of importing one library that does lots of things just for a single task.

  4. If you are using a "slow" language, like R or Python, profile the slowest parts of the application and code them in C++ and pack like a library for your target language, this goes a long way in optimizing your programs when there is none left to optimize in the "slow" language.

  5. Use each tool for it's purpose, ie SQL for data and data transforms, groupby etc goes a long way, Java for server apps that run all the time is good, but extremely slow in starting a Java VM so for client apps gives it a slow start and the memory collection makes programs slow too, hence minecraft's performance issues, for videogames and such C++, python etc.

  6. If you really want to learn hardcore optimization get into CUDA / OpenCL and GPU programming, it can go a long way into understanding how memory and parallellism works.

  7. Fork is your friend for heavy CPU apps.

1

u/ginjaaah Aug 05 '20

Use photonic computing hardware and ditch those heavy electrons

1

u/FoCoCS Aug 06 '20

by making it run daily and reduce the intake.