r/AskProgramming • u/Brussel01 • Jul 27 '21
Is writing efficient code even a thing in the real world?
Hey there,
Last year I have just finished a university course and for the last 5 months have been working in a junior development role (full stack developer if it matters).
Before this time recruiters would ask technical questions where you had to try find a solution with the best algorithm and complexity you can. I always enjoyed problem solving and doing stuff like this.
Now that I am actually working the reality seems to be different. It feels more like i'm encouaraged to go with the dumber solution or brute force solution more often. I have discussed some solutions that might be more efficient with my senior only to be told we should go with the brute force one since it will be good enough and is easier to understand and easier to maintain.
So far I have never had to use any advanced techniques like dynammic programming, complex structures like binary trees, etc.
So I ask, is efficient code even user if ever? Why are these concepts drilled in and endlessly practiced on sites like leetcode if the dumber solution is preferred? Or is this just my experience?
Thanks
47
u/mikeshemp Jul 27 '21 edited Aug 03 '21
A lot of being a mature engineer is understanding the trade-off here: when is it better to keep code simple? When is it better to optimize? There's no single right answer.
If you're writing a GUI and there's a brute force solution that's easy to read and write and takes one millisecond to run, vs a convoluted piece of code that takes 2 microseconds...I go with with 1 millisecond solution. Yes it's 500 times slower, but what does it matter if we're just updating a GUI, the user can't possibly notice the difference between 1ms and 2usec.
On the other hand I once worked for a big software company that rhymes with poogle and they discovered that optimizing the bloody hell out of a few basic functions like memcmp would save the company a million dollars a year because that function runs zillions of times a day on zillions of machines, and when you add up the cost of all the CPU cycles at that scale it makes a huge difference.
The best engineers find places where optimization has high impact and ignore the places where it doesn't matter.
24
u/YMK1234 Jul 27 '21
There seems to be a lot of implications here that maintainable code is not performant (for whatever performance metric we are optimizing). This is simply wrong in most cases. It is much more important to pick appropriate algorithms and use them in well structured and maintainable code rather than engage in arcane hacks that make the code less readable.
Also efficient code might not be what you think it is. Always profile the Code to optimize first. Quite often the time is not spent where you think it is.
4
u/andoril Jul 27 '21
I think this is more of a comprehension thing in this case. The easier someone can comprehend how something works, the easier it will be to maintain.
For example there's a list of integers, where you know it has at maximum 100 entries at all times and you want to find the biggest integer.
You can go ahead and sort the list and afterwards convert it to a binary search tree and search over it. To understand what's actually happening, I have to know the sorting and the search algorithm.
This problem can also be solved by just iterating over the list once and just comparing a current highest value with the current value from the list. To understand this I don't need to understand more complicated algorithms, thus it becomes easier to maintain for a lot of programmers.
I agree, that it's more important to use an appropriate algorithm for the problem at hand, but often times people tend to prematurely optimize, by choosing algorithms, that are - on paper - more efficient.
5
u/anamorphism Jul 27 '21
in your example, the simpler approach is also the most efficient one in various scenarios, though.
it illustrates the point well of a lot of the comments here.
if you just need to find the largest integer in a list 'once', then you're wasting resources building the data structure that leads to more efficient look-ups.
in that case, as /u/YMK1234 stated, the code is both more maintainable and more performant.
even if you're looking it up n times, you need to look at a whole bunch of factors to determine which is 'better' for your situation.
1
u/Fidodo Jul 27 '21
Yes, optimized code can absolutely be readable and maintainable, but the question is more what are you prioritizing. If you're prioritizing maintainability that doesn't mean you're not going to choose an equally easy to maintain optimized version over an unoptimized version, it just means that if the optimization isn't easily maintainable you're less likely to use it.
15
u/KingofGamesYami Jul 27 '21
There are multiple things you can optimize code for.
Readability
Programmer time
Execution time
Memory usage
In general, we optimize for readability and programmer time. Execution time/memory is optimized for only when there is a clear problem, because programmer time is expensive. If I spend a day optimizing something that could've been solved by upgrading hardware for less than $200, the company just lost money.
An example of an inefficient, but effective algorithm is the recursion I used to validate an acyclic graph. It was bad, but because I know n is always small (max of ~10), I wrote the simplest code to get the job done.
An example of an inefficient, but ineffective algorithm is the method I replaced with a stored procedure. The original caused problems because it loaded the entire database in order to filter out rows of interest.
Simple performance testing can reveal the location of these problems (if any) and avoid optimizing your code for the wrong target. In my case, I ran 1 million records through the second algorithm. Original took 30s, the updated one less than 1s.
9
u/Loves_Poetry Jul 27 '21
Yes, efficiency is a thing, but your optimizations will rarely be in algorithms. They will usually be improving caching strategies, changing the shape of your data or reducing the amount of data needed. These are all linear optimizations, but they are the optimizations that matter
4
u/YMK1234 Jul 27 '21
At least "changing the shape" can be anything but linear. Parsing a list into a dict once if it's looked up often by a key yields o(n) -> o(1)
6
u/spudmix Jul 27 '21
CPU time is cheap, developer time is expensive. I had the same realisation as you when I was just starting, but ultimately it becomes kinda obvious with experience. Most use cases simply do not warrant any kind of optimisation at all, and for the remainder where it does matter someone's probably made a nice library to do it for me. O(n) doesn't matter when n is small. A query that runs once a day doesn't can generally take as long as it wants.
You may encounter more or fewer optimisation problems depending on your solution and domain, but in general don't expect to be taking the "smart" way very often. Creating a well-architected, maintainable, beautiful code-base with a few hot loops or queries optimised is the usual target.
6
Jul 27 '21
It probably depends on what it is you’re working on.
For “normal” business applications, websites, etc, you probably just want stuff to work, be maintainable, and allow your successors to be able to understand how it works.
It’s probably going to be real time systems (missile computers, cars, life support machines, etc), financial stuff, video games, and so on, where you need predictable and/or tight performance.
A website visitor won’t notice a few milliseconds delay, but a guy about to get a missile up his arse will.
5
u/pastaKarhai Jul 27 '21
The algorithms you learned in college are already implemented there are libraries for that.
Most of the optimizations are about techniques than the algorithms in professional development i.e lazy loading, in-memory caches, saving multiple fetches, or memory leaks.
3
u/Fidodo Jul 27 '21
A lot of the time it's much less about needing to know how to write an optimization, but rather just knowing what optimizations there are and knowing when to use them. As you said, most of these things already have libraries for them, but you still need to know what solutions you need to fix a problem.
4
Jul 27 '21
Yes. You fetch on indexed table columns (indexed using btrees)
You sort a list into a map for O(1) lookup instead of iterating every time
Its the little things that add up
4
u/SV-97 Jul 27 '21
It depends on what you do. You said you're in webdev so you generally don't do stuff that requires super high-performance; what matters more is maintainability and that it doesn't take ages to write. There's other things like computer graphics, real time systems, compilers, scientific computing etc. where performance is much more important. I'm for example working in scientific high performance computing and you can guess at how important performance is in this field - it's literally in the name.
3
u/cyrusol Jul 27 '21
It's all a matter of cost.
See, it makes sense for a company to optimize parts of their code for CPU cycles or memory consumption if the computational resources cost like a couple 100k dollars a year.
A real world example would be frontend performance for ecommerce platforms. Data shows beyond 3s time to first interaction means a significant portion of users leave the site before even using it. Which translates into losses of potential customers. That's where companies are happy to spend money on performance optimization.
On the other hand if the code isn't really relevant in terms of computational resources than the cost for human resources, i.e. the time the developer needs, is much more important. In that case you want to either go with the quick and dirty solution and hopefully not touch it again (best for a risky endeavour, like when entering a new market) or plan for longevity of the project and go with a maintainable, easily understandable solution.
3
Jul 27 '21
In the end the question comes down to: how will it scale?
If you're operating on a list of enumerations of very high level categories of stuffs in the company or over a list of modules once in a while, nobody will care if you do an O(n4) even, or O(2n) or O(n!), as long as the code is readable and clear.
However if you're operating on something that is expected to grow significantly, then readability might take a second stage.
Because, really, what matters is just the end cost of developing and running the software:
How long does it take to create the software and how many people you have to pay for that period?
How many people you'll have to hire for the years you'll be using the software, to maintain it, fix bugs, add necessary updates and features?
How easy is it going to be to hire those people (people don't want to work on shitty codebases, shitty environments, or with obscure technologies)
How much hardware or IaaS you're going to need for this whole thing to run
When it comes to writing code, you have direct control over all of these.
If you write the fastest code, you're gonna save on (4), but everything else is going to take a hit. If you write easy to read code, you will probably win on (1) and (2), and even (3), but you're gonna lose on (4).
But if you have a place in the code where you have to decide between 10 and 10000 lines, and that makes a difference of running for 2h vs 2 seconds, the choice is obvious: speed wins.
1
u/Ikkepop Jul 27 '21
As a "full stack" developer you will likely never have to do it. The web is usually a pretty mundane area to work on and maintainability and rapid iteration is the name of the game. However usually atleast understanding how to make an efficient database will help you if you encounter big datasets. That said, efficient code is a thing in specific areas of development, for example game or game engine development, scientific computing, fintech, embedded systems and many others. If you want to write effficient code, the web is usually not the place to do it, unless its on a scale of facebook or youtube.
1
u/Fidodo Jul 27 '21
Even in webdev it does come up quite a bit, but you tend to just not notice it because you're normally doing simpler optimizations because your target for performance is 100ms so lots of things that could be optimized don't need to be since they're not causing problems. If something takes 100ms to run and could be optimized to 1ms, then it's pointless to fix because the user won't notice that much, and if it's frontend code it's not even your resources that you're using to execute the code. If the optimized solution increases the bundle size then it's actually worse because you're trading upfront load time for an optimization that's not even needed. 100ms is quite a bit of leeway which makes it much rarer when you actually need to optimize something on the algorithm side. Most frontend optimizations are actually tooling problems, not algorithm problems. Things like setting up your project to allow for things like tree shaking and hot module loading are much more important than algorithm optimizations most of the time.
1
u/QzSG Jul 27 '21
Real Time Operating Systems and life or death software would like to have a word with you
1
u/LordAlfrey Jul 27 '21 edited Jul 27 '21
Having maintainable and understandable code is, in a sense, an optimisation. It makes the work surrounding the software better, more efficient, less prone to unexpected behaviour and error, typically, which is valuable.
I think finding a balance between the two is the real optimisation.
1
u/Ran4 Jul 27 '21
You're completely right in that 99% of the time, stupid code beats smart code, in application code.
And yes, it's a problem that plenty of people are taught dozens of software patterns that shouldn't be used 9 times out of 10.
But in order to write your application, you need libraries - and it's usually not until you're writing these libraries (iff you need to write one yourself) that you need to know and use various algorithms, dynamic programming and so on.
For example, if you're writing a commercial web application, implementing your own sorting algorithm is almost always the wrong choice - use one found in a standard library (or similar) instead. But someone had to implement the sorting algorithm that your standard library uses.
1
u/funbike Jul 27 '21
Yes, but often not. Sometimes it makes sense and sometimes it doesn't.
If you are looking for a one-size-fits-all answer, there isn't one.
For small datasets for a small or medium number of users on a powerful server, it's no-brainer. Developers are usually more expensive than servers. Do the brute-force method.
However, on a IoT device with limited resources it might matter. I just worked on a tiny battery-powered bluetooth device the size of your fingertip (well my team did. I did the backend server work). We had to make the code small and power efficient.
Also, if you are dealing with large datasets, it will matter. I'm about to do a matching/searching algorithm for millions of records. I need my algorithm to have the smallest growth possible (i.e. big O)
Whether you optimize is a simple problem of math and economics. Which will benefit the company most?
1
u/icecapade Jul 27 '21 edited Jul 27 '21
The dumb/naive solution is fine until it isn't. Most of the time, you may not need to worry about writing efficient, optimized code, but every now and then, you might. And when that happens, you'll be glad you have the ability to do so.
Case in point, I recently had to diagnose a bug where some code written by our client would hang when it was run on certain large datasets. Turned out the programmer who'd originally written it had a poor understanding of algorithms and time complexity. His implementation was basically O(n4 ) and would have taken literal millennia to run on some datasets. I rewrote it so it was O(n) and reduced the runtime to seconds.
I don't usually have to optimize code, but when I do, I'm glad I have the background to make it happen.
1
u/Dogburt_Jr Jul 27 '21
It depends on your application. If you're working in a cloud with no time constraints for processes you're under the assumption of unlimited time and resources available to you since clouds are designed to be distributed.
1
u/v4773 Jul 27 '21
Optimization is art of its own. Most people i have talked to At this sort of things are self learned optimizing stuff. Its not usulle teached At school of any levels.
1
Jul 27 '21
As a general rule, readability is way more important than performance. Computers are cheaper than developers. Code which takes longer to run is often not a big deal, but code that is hard to understand means that it's costly for other developers to make changes.
Premature optimisation is often a problem. Spending a long time writing a perfect algorithm means that:
You're often wasting your energy if perfect performance is not necessary, and
it might mean that your solution is less readable to other developers.
the exception to this would be critical parts of an application which are hit many times and performance actually becomes an issue. For example, some code inside a loop which is running for every element of a large data set. But still, the general rule would be: write clean code first, then optimise as necessary.
As an example, consider the famous fast inverse square root code from Quake 3 Arena.
float Q_rsqrt( float number )
{
long i;
float x2, y;
const float threehalfs = 1.5F;
x2 = number * 0.5F;
y = number;
i = * ( long * ) &y; // evil floating point bit level hacking
i = 0x5f3759df - ( i >> 1 ); // what the fuck?
y = * ( float * ) &i;
y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
return y;
} This code is super fast. But it's also weird, and it's very hard for a new developer looking at the code to understand it. You would generally not write code like this in situations where performance is not critical. It's only OK because the performance of this method is massively critical: it's called a huge number of times because it's an integral part of 3d rendering.
1
u/amasterblaster Jul 27 '21
efficient is fast, bug free, and easy for a the dumbest human brain to read. This is best.
You will notice that your solutions likely fail one of those criteria. Most juniors do not understand the last one, because they have never managed a team. When you do, you will begin to find fancy solutions annoying or tiresome.
1
u/WJMazepas Jul 27 '21
Efficient code exists out there, but It depends on the company culture, values and market.
Startups generally wants your product delivered fast and wants to test a lot iterations of the product until they found their niche. I worked in one startup that had a 5 year old codebase but already had a lot of hacks and unused code because they never had the time to properly implement new features, they just needed to implement then fast. Probably you will want to avoid companies like that.
But other companies prefer stability and performance, i knew a guy that worked on a financial company that made systems for stock markets and he told me that new features took a long time to be delivered, It had to be planned, tested extensively to minimize every possible bug to appear in production, so i imagine that companies like that do prefer a quality code.
So i would say that you should look for different companies and check their values on that.
1
u/porkchop_d_clown Jul 27 '21
So, in my day job I'm writing system software for top500.org sorts of machines. I've been a programmer for nearly 40 years and I'm still learning new tricks to make my code more efficient.
1
u/Fidodo Jul 27 '21
Depends on a lot of factors. How often does the code need to be run? How quickly are the results needed? What's the absolute magnitude of the execution time? Is it cheaper to just beef up the hardware instead of paying for extra development? What's the use case for the outputs?
In practice you normally don't need to super optimize code because weighing the cost of development resources needed to optimize the code doesn't make it worth it for the benefits most of the time.
1
1
u/pragmaticprogramming Jul 27 '21
A lot depends on the type of coding your doing. Optimizing your SSD firmware, or video card drivers will be a big deal. People compare the performance differences between different driver releases.
Operating systems and websites will be optimized too, but usually in different ways. They'll lazy load as much as possible, so the OS / page appears to load faster, and allows user's to get working quickly.
I doubt apps like Word or Excel will be optimized much, but video / photo editing will be to some degree. They are pushing the hardware closer to the edge.
Enterprise code will be optimized when certain areas of the code run hot. If you find a web services is getting hit with 1000 TPS, you'll probably want to tune it. Cutting that back 10% might have a very real hardware cost savings. But, a service that's getting 3 TPS, probably not worth worrying about.
1
u/myearwood Jul 27 '21
Practicing writing crappy code means when you need to make something important it will take 10 hours when mine will take 10 minutes. There is no need to write such code.
62
u/khedoros Jul 27 '21
You optimize for efficiency the application's hot paths, but those are often down in the core of things. A lot of code isn't actually called that often, and in those places, it usually makes more sense to optimize for maintainability