Podcast Lookup

Optimization

Programming Throwdown

  • August 31, 2016
  • 1 h 16 min
  • Episode 57
Episode page
About this episodeThis show covers software optimization (how to make software run faster). Show notes…

This show covers software optimization (how to make software run faster). Show notes: https://www.programmingthrowdown.com/episodes/57-optimization

★ Support this podcast on Patreon ★

Transcript

From the publisher

This transcript comes from the podcast’s own feed, shown as the publisher wrote it.

Optimization

00:00—
  1. A

    Programming Throwdown Episode 57: Optimization. Take it away, Jason! Hey everyone.

  2. B

    I wanted to start with a public service announcement. And I've seen this so many times; it just absolutely drives me up the wall. And it's one of these things—I don't know if I'm getting like becoming a crotchety old man or whatever—but you know, I saw this. So I'm going to kind of exaggerate, but basically someone said, 'Oh, there's a one percent chance of doing this event, so I have to do it 100 times to get it.' And you see this a lot: like, 'Oh, there's a 10% chance, so that means you know you have to do this 10 times.' Or you see this a lot, and it just absolutely drives me up the wall. It doesn't work that way. Like if you have—if you have a one percent chance of doing something, it doesn't mean that you have a hundred percent chance if you try a hundred times. It means that it's actually more complicated than that. And I'm not going to like go into the formula or anything like that. It's actually—I can go to it's pretty simple. It's just if you have a one percent chance of doing something, then that means you have a 99% chance of failing. So the chance that you succeed even once is one minus the chance that you fail every time, right? So if you have one percent chance of success, you have a 99% chance of failure. So if you do 0.99 to the hundredth power—and I will put this into WolframAlpha—but if you have 0.99 to the hundredth power, it is not a hundred percent. Let's see what it says. This is really exciting radio right here.

  3. A

    I like that. You.

  4. B

    Called it Radio 36. So, so if you have a one percent chance and you do have a hundred attempts, then one minus 0.36, so 0.64. So you have about a two-thirds chance of succeeding at least one time out of a hundred. And just—you know, I've been looking a lot at like, you know, polls, and you know, like it's politics season, and so everyone tries to be a statistician, and that's cool. I think this is one of the few times of the quarter year it's one of the times where people really care about statistics, which is cool. But don't make this mistake; it drives statisticians crazy.

  5. A

    Good point. And it should also be pointed out that if you think about the formula as you were saying it, as you get closer, the—you start slowing down, right? So the—you're taking off a percentage each time, but the amount you increase gets smaller. I'm saying this really poorly, that basically so you did it 100 times and you got to two-thirds chance, but if you do it a hundred more, you're not going to again; you're not going to get to a hundred percent. You're going to just decrease two-thirds more, right? And so like the more you do it, you're approaching a hundred percent chance, but you'll never actually reach a hundred percent chance except at infinity, right? Because

  6. B

    there's always going to be some chance that you fail every time. Like it had that chance, that possibility has to exist, right?

  7. A

    It's a non-zero possibility.

  8. B

    Right. So yeah, if you're curious about this thing, it's the binomial distribution. You can go on Wikipedia and learn all about it. Yeah, it's pretty interesting in general, like even if you're not really into stats. Just reading about the different distributions is pretty interesting because each one comes from a different phenomenon in nature. They're all derived from like people's experiences with the world, and just reading about them is actually pretty interesting.

  9. A

    Every time I read about statistics, I'm reminded how bad I think everyone is—pretty bad at it. And I think I guess even statisticians probably have to be very conscious in their thought about when they hear things and what they mean because I feel like humans are generally just kind of bad at odds.

  10. B

    Yep. Yeah, totally.

  11. A

    The one that we've talked about before, but for people who missed it, there for sure. Whatever the Monty Hall problem is, always the best example of that. I

  12. B

    think. Yeah, although you know that one is kind of confusing. Like I so have we talked about it before, should we give a brief description? We'll recap it. Someone actually emailed me today to say that when we said something, we should say it again. Yeah.

  13. A

    that makes any.

  14. B

    Sense. So, the Monty Hall problem is this: you have three doors. They tell you that one of the doors has a car, and the other two doors have something else—it's like a goat or something. Yeah. So, you pick a door, let's say Door Number One. Then what the host does is he picks not the door you picked—that's the key point. He had if you say I'm interested in Door Number One, then the host has to choose either Door Number Two or Door Number Three and open it for you. But he...

  15. A

    knows what's behind each door, so he will reveal a door with a goat.

  16. B

    That's right. That's right. So, he knows. So if there's goats in Doors Two and Three, he'll pick one at random—fifty-fifty chance. If there's a car in one of those doors, he'll pick the goat door. But the thing is, then he'll come to you and he'll say, 'You chose Door Number One. I showed you what's behind Door Number Two. Do you want to stick with your choice or do you want to change choices?' And we'll...

  17. A

    reveal what's behind your door, and you get whatever's behind your...

  18. B

    door. That's right. And so you should change. Well, so the question is, does...

  19. A

    it matter if you stay or like what is the best strategy?

  20. B

    And and the answer is—is that you should change your guess. And it seems like doesn't make sense, like why should you change it? But the key is that the host can't open the door you chose. So because he can't do that, he has to choose one of the other two doors and he has to choose a goat door. And because of those two things, he's giving you information you didn't have before. Like it seems like he's choosing a door at random, but you are actually forcing him to choose a door by, you know, picking a door in the beginning. You're sort of forcing his hand—not always, but sometimes. And the fact that you did that carries some information. So it's one of these like cyclical paradoxes, but it's super interesting. You should look...

  21. A

    it up. It is really challenging, and even when I know the answer, I still don't find it intuitive. Like I have to reason about it. But the funny thing is, the two strategies aren't even close. Like always staying or always switching—always switching yields significantly better odds than always staying. Yep. And the more doors you have, the better. You're I guess it diminishes, but yeah, right. That's right.

  22. B

    I mean as the doors go to infinity, then the fact that you forced him not to pick one of...

  23. A

    them becomes negligible, right? Okay. So I was emailed as well. I actually think this was last week or two weeks ago by—oh, I have it here on the date. When was this? Oh, yeah, so a week ago by Abdullah, and he was saying, or yeah, they were saying that four years ago, so we're in the Olympics now in August, and four years ago it was also Olympic time. I guess that would have been in London, and Jason made a prediction about the 2016 Olympics. That's

  24. B

    Right, I predicted that we would be able to watch what's it called? I forgot. There's a thing where you can watch videos on BitTorrent. It was like pretty hot four years ago, but the idea is, you know, think of like Netflix, but it's all of the packets that comprise the video are just coming from random people on the internet, but it would be a Netflix-like thing. I think it's called BitTorrent Video, but it's a Netflix-like thing. You go in, you just start watching a video, but it's all crowdsourced. No one's paying for the servers, and I kind of felt like the Olympics in 2016 would be served over one of these, you know, peer-to-peer anonymous peer-to-peer kind of things, and it didn't happen. Actually, I don't think can you even watch the Olympics online without a cable subscription?

  25. A

    I don't think so.

  26. B

    I'm sure you can.

  27. A

    Watch clips, and there's probably like quote-unquote pirate streams.

  28. B

    Sure, yeah, but you can't get a feed like an official, you know, Olympic feed, which is really kind of a shame because the whole point of the Olympics is like amateur athletics, not anymore. Yeah, I mean, I kind of thought four years ago that that, you know, but instead of instead of peer-to-peer Olympic streams, we have all these like NBA superstars, which is, you know, cool too. Well, I thought I was

  29. A

    going to blindside you, but apparently you had forewarning of this prediction, so that's okay.

  30. B

    Maybe I'll try.

  31. A

    Again. So my first news article is, and bear with me, this is going to be a little strange. I guess an interactive Sudoku zero-knowledge proof. That's the title of the article, and this is something I didn't know about. I was like, 'Wow, this is weird. What is this?' And then I clicked on it, read about it, and I was like, 'Whoa, this is awesome.' So if you that sounded really surferish, I apologize. If you've heard of before zero-knowledge proof, I kind of heard it in passing often associated with like blockchain stuff, um so Bitcoin and Ethereum, and the like. And zero-knowledge proof is a way of you solving a problem, and for instance, like I solve a problem, and I want to communicate to Jason and prove to him that I have a solution to the problem, him to know that I have the solution to the problem without telling him the solution to the problem. Um so okay, so one of the things would be like if there was a really large number, and I had factored the number, you know, it was a composite number, and I had factored it, or it was a prime number, and I had proved it was prime, and I actually don't know how. I would work with primes. I'm just making this part up, and I wanted to communicate to you and prove to you that I had actually done that work, but I didn't want to communicate to you what the answer was until you accepted my proof. Uh this is this is kind of like a way you would go about doing this. So in this example, and this article actually links to by the same author a previous article they had written about more generally zero-knowledge proofs, but I thought the Sudoku one, so you should read that as well. But the zero-knowledge Sudoku one was kind of cool because it was a very easy-to-grasp explanation. The other one goes through a graph coloring problem, which is a little more abstract, but basically, well, Sudoku

  32. B

    is a graph coloring problem, right?

  33. A

    I don't. Yeah, if you told me it was, I would say that would agree with you. If you ask me, I don't know.

  34. B

    Oh yeah, Sudoku is a graph coloring problem where you have nine colors and you draw edges between all of the squares that can't be the same number. You know? I'm saying, oh.

  35. A

    Okay, so it isn't a graph in the way it's presented though. It's a but you could represent it as a graph. I got it. Yes, yeah, yeah, right. I hadn't thought about it that way before. Um but I guess it makes sense. And so, but I guess like the rules of Sudoku or if you've played it before, what this article does is explain it and then actually has like a little—I guess we would have called an applet before, but applets aren't a thing anymore. So it, yeah, that's kind

  36. B

    Of sad there's actually I don't even know. I guess because Applets aren't a thing and Flash isn't a thing, so I guess it must be an HTML file.

  37. A

    Or JavaScript. Yeah, um, and what this is is if you've kind of played Sudoku before, this would be a way given a puzzle and you know a few of the numbers filled in, and I solved it and filled in all the numbers correctly, and there's always a unique solution to a proper Sudoku puzzle—only a single unique solution. Um, and I wanted to communicate that to Jason and him to know that I completed it without giving him the answer. And this walks through how you would do it, and it has both sides, like what my side would be as the solver and what Jason's side would be as the checker. I think they call it mine would be the prover, and I forget what the exact terms are anyways. Check out the article; it's really informative, and it's something I didn't know anything about other than hearing the term in passing, and now I actually am very intrigued. I kind of want to dig into it a little more, um, and understand. And so if you've ever been curious about it or heard about it or never heard about it before, I'd recommend this article. You either search 'interactive Sudoku zero knowledge proof,' or we'll link in the show notes. Yeah.

  38. B

    This is really cool. I mean, they literally have a thing where you can fill out a Sudoku board and it'll show you how to do the verification and everything, like it'll step-by-step walk through it. Yeah.

  39. A

    And so this, and then in the previous example, a previous article they wrote, they do mention here like if I wanted to use an escrow account in the blockchain, how would that work? Like how would I have something that I wanted Jason to know that what I had was legitimate. Him put money in the escrow, send it to him, and basically have the blockchain itself kind of do the brokering so we don't have to rely on a third party, and that was really interesting as well.

  40. B

    Cool, very cool. Um, yeah, my news is OpenStreetMap city blocks. This is pretty cool. Um the idea is OpenStreetMap. We may have talked about it before. I've actually used it for several projects. Um OpenStreetMap is as it suggests, it is a open source map of all the streets, and it also does, you know, coastal and, uh, you know, forest lines, all that stuff. So imagine, you know, you have some cool project where you want to count the number of streets in your neighborhood or in your zip code or something like that. You can download the OpenStreetMap data set for your zip code, and they even have a little map view where you could draw a rectangle and and crop out your neighborhood, and you will end up with this XML file, and uh you can parse that file with, you know, they have a bunch of tools, and you could count like how many streets are in my neighborhood, how many traffic lights are in my neighborhood. You can even plot them like on the screen and stuff like that. Um so this guy used Python GeoJSON, which is uh I actually haven't heard of GeoJSON, but I think it's a JSON format um with like a spec for geo data, and uh he actually walks through with Python code how to determine um the city blocks in an area, and it's it's just one of these kind of cool step-by-step with good visualizations and tools uh and source code um on how to do any type of like mapping data. So if you're into that, uh if that project sounds cool, uh check out what this guy has. It's pretty interesting.

  41. A

    Working with geospatial data is always kind of cool because it kind of is inherently visual, or I feel like it is, and so you always get to make a cool map or something at the end.

  42. B

    Yep. Yeah, totally. Also.

  43. A

    We keep calling these news, but I think all of ours are links this week or this month. Um yeah, my next link is actually been around for a while apparently, but I had never seen it before, and I'm thoroughly fascinated and adding it to the queue of things I need to work on or want to play with in spare time, which I did. I will say I have opened Still on my computer the puzzle competition that we talked about last month, and I didn't go to any of them yet. I meant to do it before the show, and I just didn't. So I still owe everyone my attempt at trying to do those puzzles. All right, cool, but these puzzles are called the CryptoPals Crypto Challenge, and this is a group of puzzles around breaking cryptography, so everyone has kind of heard that for instance the SHA-1 hash is broken and you shouldn't use it like it's not secure. Um but I would venture to say most of us don't know what that really means. Yeah.

  44. B

    Have no idea what that.

  45. A

    Means? We also know like you W oh man, I always forget it because now we're all WPA, but what was it before WPA?

  46. B

    On Wi-Fi WEP.

  47. A

    WEP is is encryption is broken. Um and so these set of crypto challenges start out with some programming tasks to learn, and then they build up on that by having you break encryption using the tools you've built, or at least that's what I.

  48. B

    gather from kind.

  49. A

    of skimming it and the kinds of attacks you're doing and analysis you're doing, increase in complexity as you're working through them, up to some kind of like real grade. It seems like an actual encryption, so these aren't just toy, you know, cipher schemes; these are like real things with explanations about them. So I feel like working through it, you would learn really well about both the attacks and maybe even being able to do your own attacks, and also about the things themselves because what better way to learn about an encryption scheme than by figuring out how to

  50. B

    break it? So when they say broken, do they mean that they found some assumptions you can make where you don't have to brute force as much, or do they mean that computers are just fast enough that they're not, you know, the keys aren't long enough or something?

  51. A

    I think it means both ways. So in the first case, people might say that like 32-bit, which no one uses, about like 32-bit RSA encryption is no longer secure, and what they mean by that is that with enough compute power, factoring a 32-bit encryption key is so fast that your message won't stay secure for very long or long enough. In other words, instead of lasting 100 years, it would only be secure for maybe well in 32-bit, really short. But that's kind of what they mean. But there's also, as you pointed out, you could detect a flaw. So in that way, it's not kind of broken; it's just insecure. But you could also find a flaw, which means that even though you think you have X bits of safety, you don't because there's some flaw that allows someone to exploit something and find a way around that. Where instead of factoring—so for instance, in the RSA algorithm, if someone figured out oh, you have a 256-bit number, but I don't actually need to factor the 256-bit number; I only have to factor this 8-bit number instead. Like then that would be kind of

  52. B

    broken? Got it. Yeah, that makes

  53. A

    sense. At least that's my understanding, and that's kind of both—both of those ways. Cool. So I'll have

  54. B

    to check this out. I love things like this. Yep, cool. Um yeah, mine is pretty simple. So there's, you know, obviously a lot of programming languages and new languages, you know, coming out all the time. As languages come out, I think we did this with Rust a long time ago as languages, you know, first came out. We usually cover them in something like this because we don't know really what the impact is going to be. And this is one of these languages; it's called Simit. It's a language for physical simulation. Um this is pretty cool. The idea is um, you know, it's all on one machine, but it handles these. So like what's a good example of this? Like let's take for example some type of water dynamics, like you have droplets of water that are, you know, bouncing around in some physical engine, right? Well, you could start coding this yourself. You could say oh, I'll have, you know, a Water class, and the Water class will have a velocity. And then all of a sudden, you find oh, I have 300,000 classes, and my program is just breaking apart because um because of, you know, handling all these classes and virtual functions 300,000 times and you're updating it 60 times a second. Like that's where sort of a lot of the programming principles kind of fall apart when they're at that huge scale running that quickly. Um and so that's where you really need somebody who can, you know, both be good on the architecture side and also give you incredible performance. And so that's where a lot of these kind of niche languages uh to where they're important. So Simit runs on CPU or GPU, and ideas, you um, you know, kind of explain the dynamics for a particular particle, and and you describe how it—and I'm saying particle, but it could be any, you know, units, right? And then you describe how that interacts with with other ones. You sort of try to describe the envelope of these interactions and then it breaks apart your uh simulation and tries to run it um, you know, on as many cores as possible on a GPU or CPU. And as long as you can model your program like as long as Simit—you know, like what Simit Simit can't, you know, it won't let you do like for loop and do individual things on each element and things like that, right? It's kind of restricted, but as long as you can uh describe the dynamics of what you're building in Simit, it's insanely fast. It like completely blows away um, you know, MATLAB and R and all these other tools.

  55. A

    Time for book of the show. Book.

  56. B

    Of the show. My book of the show is a set of graphic novels which I found is is the adult is the like the old man way to say comic books, but uh mine's called The Manhattan Projects. It's pretty cool. Uh the idea is um so for everyone doesn't know the Manhattan Project was the code name for the atomic bomb. Um so The Manhattan Projects is a set of comic books where you find out that the atomic bomb was just one of many Manhattan Projects. Um and I'm not going to spoil too much, but but uh, you know, a portal to, you know, an alien planet is another one. Um And there's a variety of these projects, and it kind of uh takes the whole like military secret and scientists who, you know, are researchers, but also military and dealing with, you know, policy, you know how you're building something so cool, but at the same time it's so dangerous. It kind of tackles that. It has some amazing quotes in it, like really kind of funny and prophetic quotes. Um I read the whole thing. I think it's like 30 or 40 volumes. It's uh uh it's really, really good. Highly recommended.

  57. A

    The art style is kind of interesting. It's like pretty gritty. Yeah.

  58. B

    Definitely. I mean it's—it's that's actually one thing that we should probably mention is, you know, it's pretty kind of violent. Um if you have like kids in like middle school, high school, like maybe this wouldn't be the right thing. Well, high school probably fine, but like yeah, it wouldn't be something you would give to like your five-year-old son or anything. Oh, or daughter, but uh it's definitely for adults only. Uh, you know, it's got a lot of language, got a lot of violence, but uh it's really cool. Um it's a fantastic read. Yeah, I've

  59. A

    Never thought about that. I guess for our book recommendations, at least the fiction ones, we probably should have some sort of like rating—kid approved? Yeah, well, most of them.

  60. B

    Have most of them have a rating. I'm trying to think.

  61. A

    Back to all of my sci-fi recommendations and seeing if I've said anything. Okay, it's all right. I can't worry about it.

  62. B

    No, I mean Amazon. I'll tell you right away.

  63. A

    The rating? So my book of the week is Theft of Swords. This is interesting because it's a—I guess it's a volume. I don't know how they were originally released. I haven't looked into it because I try not to read too much about a book until I've read it yet, but there's been two books within the book, and each one has been pretty self-contained. So I guess it's a volume, and there were—there were kind of two stories in it, and they were related, but you could have kind of stopped halfway through the book and like been happy. It was a story, and I'm not quite done with it yet. I'm probably like five percent away from the end of this book, but I still am going to recommend it unless like I come back next week or next month and I'm just—the ending was atrocious and totally not worth it. Other than that, I feel like it was a really good book. Cool. So this is a fantasy book about—I always struggle to not give away too much about two thieves who are kind of working together and get caught up into something that someone is trying to use them, but turns out not to happen as they wanted, and they get kind of tied up into some political goings-on and kind of their story about being thieves in this world of political intrigue. It's kind of interesting.

  64. B

    Cool, sounds awesome.

  65. A

    So it's a light-hearted book, and I've been listening to it on Audible. And Audible is a sponsor of our show, so if you're interested in getting an Audible subscription, which I use to pass my drive to work—I've been a paying subscriber for I don't even know how long now, several years—but if you go to audibletrial.com/programthrowdown, you can get a one month free, which is essentially one book. And then after that, you know the various plans, and if you don't like it, you can just cancel it and keep your book. And that helps out the show. And I actually do recommend Audible if you have a commute. People are always looking for ways to pass it, and I pass the time in the commute, and I definitely recommend Audible. I like.

  66. B

    It yeah, totally. I mean, the thing about these things like Audible doesn't like have any deal with us like we have. If you go to audibletrial.com/programthrowdown, you will help out the show like we have that, but you know we're not like shills who—you know, we only endorse things books and services that we actually use. So um so yeah, Audible is cool. Check it out. So we also have Patreon. I promised everyone I would get T-shirts made so that we could we could so you could order T-shirts. I'm totally lacking on that. It's it's not that I'm not working on it; it's that I'm not happy with the logo, and I'm kind of a perfectionist. But once I have a good logo, we'll get some T-shirts. Are you gonna are we gonna

  67. A

    get models for them because I feel like you and I modeling them will not sell.

  68. B

    Them? Oh, good point. Yeah, we need—we need models. All right. If you think we could get Michael

  69. A

    belts to wear one of our T-shirts.

  70. B

    That would be pretty awesome. The only thing is he's got those brown spots from those suction cup things. So yeah, we have Patreon. You go to patreon.com/programmingthrowdown, and that is just a like a donation. It keeps the show going. I was able to buy a microphone so I didn't have a microphone—that I got in a thrift shop, as someone accurately called me out on Reddit. So you know, buying it helps us get the equipment we need to keep the show going and all the services and all that. So we appreciate that. Long tool this show. My tool this show is—so originally around originally but a few months ago, I recommended by word, and I do like Byword, but it has this problem where it's OS 10 and iOS only, which is great until you know you have a machine like my home desktop is still running Windows. And so Google Docs is, you know, pretty close to Byword, but my big criticism of Google Docs was that it's not Markdown. And so if I want to take something from Google Docs and post it on the web or you know do something else with it, it's not in a format that's very accessible. Well, someone wrote GDocs2MD, which is a—and I haven't tried it yet. I'm going to try it later on today, but it will take any Google Doc—it's a little Chrome extension. It'll take any Google Doc and convert it to Markdown. And so I've always been a big fan of Google Docs other than this one issue, and this seems to you know a lot of people are saying that this plugin works really well. So um, so yeah, so definitely, you know, if you have any notes if you're trying to write like a book or anything like that, or if you have taking notes in class or something, Google Docs is the way to go. It's truly universal.

  71. A

    Of the show is not a game this time, which it normally is, but is I guess you say it's Scrapy, which is like scrap with a Y on the end. This is okay. The Py at the end for Python, and this is a web crawler or web scraper for Python, a library to help you write Python programs that crawl the web.

  72. B

    This before, and

  73. A

    Always said, oh, I wanted to, you know, I want to learn that at some point. Again in my giant heap of things—it switched from a queue to a heap, but nice by heap of things of, you know, to research, but I ended up with the use case for this. And I will caution that you should probably read the like user license agreement, you know, respect whatever websites say for proper usage. And please don't take anything I say as like legal advice or not. Um sorry, that was my disclaimer, but I had a use—I wanted to find out what realtor was selling the most property in my area. And you know, you can go on the website, you can look in your zip code, you can see what realtors are selling houses because selling houses at least in the United States is something that needs to be disclosed for various reasons. And so you can see when houses are sold—that's kind of public knowledge—and actually how much they're sold for as well. It typically also lists the buyer and seller, as people as well as the buyer and sellers agents that represented them. And I wanted to see who is selling a lot of houses in the area because you know if I, you know, I wanted to sell my house, I was just curious who would be someone good to contact.

  74. B

    Yeah, totally. It makes

  75. A

    Sense, but this isn't information that they for various reasons I could imagine they don't want to share or they don't have available. Um yeah, they're

  76. B

    Afraid of like a winner-take-all thing, right? Right. You know, yeah, and so it's available.

  77. A

    You could do it by hand. You could kind of enter your zip code or you know search by area and kind of look at every one of the houses and kind of keep notes of who was selling houses and how much for it, and you could kind of build this data. But that's what a web crawler does. So a web crawler, you give it a web page and you tell it kind of what data to look for on that web page. One of which would be a bunch of links like to houses that had sold in the area, and then it'll go crawl those pages, pull them down as well, and present to your program that the code for that website, and then you can collect whatever information you want out of it. And so Scrapy is actually a very powerful tool, and I only—you know, I only needed the basic tutorial to even get this working. So I'm sure I didn't even scratch the surface that supports all of these activities. So it knows how to go to a website. It knows how to get the data, pull it into a way it uses XPath or CSS selectors for you to be able to kind of look for specific tags in the website to find a URL or to find parts of the DOM, and then you can parse those, do something with it, and tell it, oh hey, go scrape these other pages. And your code kind of gets a very clean slice of the data, and then it has a way to kind of output all that data to for instance JSON. And so what I did was—or a friend did, I guess I saw a friend who did this, put it all to a JSON file. And then once you had an JSON file, you had all the data you needed. You just needed to do it once, and then I could kind of slice and dice the data however my friend wanted. It could be sliced and diced, and you could sort—you could see who sold total dollar value the most houses, what was the median price of houses they sold. All this kind of information. It was really powerful, and it was actually really, really quick to get there. It didn't take very long for my friend to code this up because this tool is really good. So Scrapy. If you ever need to do something like that, very powerful. It has all sorts of advanced functionality in there about like creating a pipeline of data to go through and how to create objects that get improved as you're moving down the pipeline. And it does for instance, often the same link may appear more than once in the web page, and it knows how to not kind of scrape that web page twice. So it'll do, oh yeah, no clobber. Yeah.

  78. B

    This is just I think you just gave the best endorsement ever for anyone who is in high school or college and trying to pick their major. Like, you know, I mean if you're in CS—like, I mean obviously all the majors are great, but if you're in CS, I mean look how cool your life is. Like you just automatically say, oh, I think I'm just gonna write a program to scrape the web and find like the most competent realtor, and like you just have like incredible authority and power at your fingertips. It's just amazing, and the

  79. A

    Thing that's interesting as well is like once I wrote it, it was very easy to say, oh, what about for neighboring zip codes? What about for another state? What about right? And then you can start to say, oh, interesting. I wonder if I had a list of zip codes for which zip codes are the highest houses selling or you know whatever. Yeah, I mean if

  80. B

    You wanted to buy like a stable? If you want to buy in like a stable neighborhood, you could just do it. Like you could you could literally like see the trends of each neighborhood, and

  81. A

    Then you could start thinking—I mean, and I didn't get this far, but you start thinking, and someone was like, 'Oh yeah, this is a great idea. You should know publish that data somewhere.' And I think that would definitely for my friend to do that would be definitely against whatever.

  82. B

    Terms? Oh yeah, you would for the underlying.

  83. A

    Data. So do not do that for personal use, you know. You could probably have just done it by hand like I said. So I'm not a lawyer, but it doesn't—it doesn't feel that much.

  84. B

    Different? Yeah, it's almost—it's nothing wrong like your friend did. Nothing wrong, but yeah, if you publish it and especially if you try to make money off of it, that's where it becomes problematic.

  85. A

    But you could imagine—I think for instance in this one, it was the last five or six months of data that was available. But you could imagine running this every month for the last month and building up trends over time. That would prove even more useful to you as the amount of data grew, like what month is the best to sell in? And there's general trends like that, but you want it for a very specific area, a very, very specific tailored need. And so to Jason's point, this is cool being in CS, but the Scrapy seems really powerful. I think I've probably come up with more uses in the future and just wanted to give a shout out.

  86. B

    To that project? Cool. Yeah, I will definitely—I usually use Wget with Dash R, but Scrapy sounds way better, so I will switch. Yeah. So.

  87. A

    I mean, that's an interesting point. You could write all of that what I just said by hand; it wouldn't be that hard. And you could cobble together a few libraries to even help you. But the awesome thing was twofold: one is that they already did all of that for me, so I only had to like—it the kind of the plumbing was all there. So I banged this out in a total of maybe it and that was because I'd never used it before, and I'm not a real big Python programmer, but I probably banged it out in a total of three hours from like having the idea to using Pandas to actually like slice the data in the way I wanted. Um, and so that was really powerful to get that best, and they have tutorials, you know, kind of devoted like if you're doing Wget on your own, you're kind of on your own a little. But with Scrapy—I mean, this is a community of people devoted to doing these kinds of things, and so it's really easy.

  88. B

    To find answers? Very cool, very cool. All right. So our show topic is optimization, and there's obviously like many components to that. So we try to start with, you know, close to the metal as possible, and then move all the way up the stack. So I guess like the lowest level would be, you know, just the—you know, the instructions that in the architecture you're working with.

  89. A

    Yeah. So I think, you know, I'm more comfortable low level, so I think I'll probably talk a lot here in the beginning, and then we'll probably shift over to Jason as we move up the stack here. All right? But exactly right. So the instructions—so you kind of framed it a little, but optimization is really broad topic. We're going to try to kind of give some buzzwords, keywords for you to look at and some things to think about if you ever encounter needing to make your program run faster or your software stack to run faster. What are the kinds of things you should be thinking about? And at every level there's—there's some amount of work that can be done, and different levels are appropriate for different kinds of projects, different parts of the life cycle of a project. And so we're going to kind of cruise through this on a pretty high speed, but the first thing is the processor using the architecture, whether it's a microprocessor or an x86 processor, an ARM processor—the instructions available to you are going to be different. And if you have the ability to choose what kind of architecture you're running on, you may be able to get certain advantages. One of the things that's interesting for instance is what is the difference between a desktop Intel processor and a server Intel processor? If you look at them kind of like at a high level, the clock speed might be the same, the number of cores might be the same, but the instruction sets available in the two can be vastly different, and the amount of simultaneous floating point operations supported, right, can be very different between a home and a server, and explains, you know, a lot of the price difference between those two. And understanding which one you have and which one you're running on will help you optimize your program for the right thing.

  90. B

    Yep. Yeah, when you look at megahertz, you know, your processor, you're only looking at the speed it takes to do the fastest one thing. But you know a processor could have, you know, half the megahertz but twice the bandwidth. And so then they're—you know, assuming you can parallelize, you know, your computation, then they're both equivalent even though one looks a lot higher at, you know, superficially. So.

  91. A

    I saw a great example of this. Someone said for the newest Intel processors like high-end Intel processors were pretty expensive, and so they actually bought Xeon, which is the server class Intel processors, and kind of did a comparison, and the Xeon processors crushed the newest Intel processor for the consumer market, um kind of in. The same price range. But the difference is if you played a video game, the Xeon process were actually pretty terrible because they were all about doing lots of little things at once, which you would do in a server serving up many, many page requests. But on a game, you're kind of only wanting to do one or two things as fast as possible. Yeah. And so that was an interesting trade-off. Other thing is we've talked about several times, so we'll skim over it, but GPU, so get into heterogeneous processing and whether you can use a GPU to offload and optimize how your process—your program's runtime by running it there. Um, and then, you know, once you have a CPU selected or GPU architecture, you can start to talk about the compiler, which is producing code for a specific architecture, and there are all sorts of optimization settings in your compiler so you can optimize for size versus speed. And one of the interesting things, and we'll get to this in a second, is that you might say, 'Well, why wouldn't I just do size?' because most of the time we're not concerned about, or 'Why wouldn't we just do speed?' Most of the time we're just not really concerned about the size of our program. But if you look at how a processor works, it has to keep parts of your program in memory. And so if you have a certain portion of your code which is used over and over again, if the compiler tries to optimize it to run as fast as possible through those instructions, once it might have a code size which is 25 percent bigger than if it optimizes for size, and if the size gets you under the limit of one of your caches and you can keep your program loaded in cache instead of in main memory, then you actually might be faster by having it be optimized by speed which is by size than by speed which is really kind of confusing.

  92. B

    I had no idea that could happen. Yeah.

  93. A

    So we've had this happen a couple times, and it's really kind of hard to predict. And it depends on exactly what process you're running on, but you kind of just got to try both, but optimize the compiler will try to do a variety of tricks for you about keeping your variables in registers instead of in memory. Um, it can do things that are complicated like loop unrolling. So if you think about, you have a for loop and you're only going to go through it once or twice, you know, some constant that's defined on it once, but like two times, like you need to go through this loop two times or three times. If you kind of write it in assembly as a loop, then you have this branch. So at the for loop, you have to first evaluate some condition. If the condition is met, you need to execute the instructions below; otherwise, you need to branch past the end of the for loop into the other code. But doing that comparison and branching are two things that cost the processor time: the branching because of pipelining, which we won't get into now, um, and the comparison because that's an instruction it has to—has to perform. If you are always going to execute that loop three times instead of having to evaluate, you know, the counter i is less than three or not, you could just run the same code inside the loop three consecutive times with an increasing counter value in between, and then you save the overhead of running the for loop processing part. And so that's something the compiler can do to try to optimize your code. And sometimes the compiler doesn't know that can be done, and you need to do it by hand. And you actually need to like—that's pretty extreme. I wouldn't recommend kind of starting off there as an optimization setting, but sometimes you may gain benefit by hand unrolling your loops. Yeah, I saw.

  94. B

    Some article a while back that said, I mean, I feel like this is a very contrived example, but they said that in some cases Java was faster than C++ because they have this just-in-time compiler, and so at runtime it could know that this for loop is only going to be executed 50 times even though the 50 was a variable. Um, you know, by the time it got to the for loop, it knew that it was only going to be 50 guaranteed, and so it unrolled the loop, which is something C++ couldn't do. I don't know how much truth there is to that today. This is also an old article, but

  95. A

    That does happen. And actually people don't—I've met people who kind of didn't know this, and it was shocking to them. The processor itself also will learn in what's called branch prediction. Yeah. So if you have an if statement, for instance, if the code has thrown an exception, you know, do error handling; otherwise, you know, kind of continue on. Um, the compiler—the processor itself as it's running your code will learn that that branch is never taken. So it always could be taken, but it'll optimistically assume that it won't be taken and then it'll start loading the pipeline with the code afterwards instead of the code inside the exception. And so as you go through that loop more and more times, you'll get better speed. And then if you ever do throw an exception, it'll be slightly slower because the code it wasn't anticipating that was going to happen.

  96. B

    Yeah, and ironically the way the processor does that is by estimating the binomial distribution, which is the first thing we talked about in the

  97. A

    episode. So it goes

  98. B

    backwards, and it says based on how many times you did or didn't take this branch, I'm going to sort of reverse engineer the confidence bounds, and then when it gets to a certain amount, then it starts doing it swaps over the prediction. And this

  99. A

    also has to do with what we were talking about before, keeping your code kind of as compact as possible, especially when there's many, many iterations you need to do. So for instance, think about if you needed to do image processing and do some operation for every pixel in the image. If you keep that code very small, then the compiler has a better chance of learning about those branches or not—the compiler, but the processor has a better chance of learning about those branches. Yeah. And so then I mentioned before cache levels, so people have heard things when processors are spec'd out like L1, L2, L3 cache sizes, and then you have RAM size, and then you have disk. So the because of the speed of light, the amount of distance you need to travel actually becomes fairly significant if you have to go all the way out from your processor to main memory. So no matter how fast your RAM ever gets, there will still be a limit to how fast data can come into the processor just because of how far it has to go travel through the wires. Does

  100. B

    the wire is it the speed of light or is it the speed—well, the speed of light sets

  101. A

    a theoretical bound. Oh, okay, got it. Right? So even if you use fiber optics or whatever, if you're like a meter away from the processor, which is an extreme, then you know kind of there's a set latency from when you decide you need something to the fastest you could get it from something that far.

  102. B

    away. Oh, and

  103. A

    When you're talking gigahertz that actually matters, which is crazy when I first learned that. But leaving

  104. B

    that aside, that's

  105. A

    Not the main problem, the biggest issue is it is very expensive to have very fast memory and to put memory on the processor itself. So the closer you are to kind of the main bits of the processor that are executing your code, the smaller you are because there's a lot of things that need to be connected on the physical processor, and there just isn't a lot of space. So then you have to go through extra sets of interfaces and out to kind of other parts of the chip to get to bigger levels of cache. And so the processor always wants to look in the closest cache because that cache is fastest. If it's not there, you have what's called a cache miss, and then you got to go out to the next cache miss, go out to the next cache miss, go out to main memory. If it's not in main memory, it has to go all the way out to hard disk, which is terrible. It means it's going to take forever in processors.

  106. B

    Yeah, I think each way it's like an order of magnitude, right?

  107. A

    Or orders of magnitude. Yeah. Oh wow, so it's really bad, right? And so when we talk about optimizing, there's a lot of things you can do once you kind of understand that—that's how the processor works—to keep the working set, is one way to describe it, the amount of data that you're operating on. If you need to do lots of operations doing it on a small set of data before moving to the next set of data is going to be faster than if you... So if you think about like I have a sequence of operations I need to do on an image, like first I want to, you know, Gaussian blur all the pixels. Then I want to do an edge detector. Then I want to do and you kind of stack up like five things, and if they were not dependent on each other—hypothetically for now—if you took a single pixel through all of those steps, that is in some ways going to be faster than doing all of the pixels through the first step, then all of the pixels through the second step, then all of the pixels through the third step.

  108. B

    Oh yeah, right.

  109. A

    Because the size of your image is going to be really, really big. And if you start at the first pixel and you go through every single pixel, by the time you get to the last pixel, the first pixel isn't in memory anymore or it's not in the closest cache anymore. And so right, a lot of optimization for memory access is built around that. And so if you look at kind of how a matrix multiply is done—if you get to really big matrices—the naive way they kind of teach you to multiply matrices by hand doesn't work that well in a computer setting, mostly because of how memory access patterns work. Memory comes that is clumped together. You kind of get close-by locations for cheap and then you operate in a smaller working set, and so faster matrix multiply operations take advantage of that.

  110. B

    Yeah, that makes sense. Yeah, a lot of this stuff—I mean, if you're doing the hope is that one percent of your code is 99% of the CPU usage, and so you know you don't have to super optimize everything, but you know something like for example, you said image processing, the part that manipulates the images at a low level, like has to be extremely fast.

  111. A

    That's right. And so there's a couple things you point out there. First of all is making sure you identify the code that it's worth spending this time to optimize. Yeah.

  112. B

    We should do a pitch for earlier. We had an episode on profiling, right? You know finding out what parts of your code are the fastest, and you should definitely check that out if you haven't already.

  113. A

    So that's a great first thing you should always do because once you start getting into these optimization techniques that I've talked about, your code does become harder to read often because it's doing something slightly non-obvious. And so you don't want to go there first unless you have to. The second thing is using tools other people have written. So you were talking about linear algebra libraries I think last episode or two episodes ago. Yeah, right? And so using a linear algebra library if you're going to do matrix multiply, what you're hopefully getting is someone else who spent a ton of time figuring out the absolute fastest way to multiply two large matrices because if you do it naively, you're probably not going to be as fast as them.

  114. B

    Yeah, it'll make a huge difference. Yep, and so

  115. A

    identifying blocks of code that are common and trying to find other people who have good implementations of

  116. B

    Those. Yeah, totally. So, let's say now you know you have a lot of data, and it's not fitting in memory or it's just super slow to access. And you know, you can't—it's not a matter of speeding up the unrolling loops or things like that. The reality is like you just have a ton of data, and you need to pull out like a needle in a haystack. So this is called, you know, an index or a reverse index. So, for example, a database if you use SQLite or use MySQL or one of these databases, and you can store, you know, a billion entries, and then you say, 'I need Patrick Wheeler,' and it just gives it to you instantly, right? But you know, if you wrote a for loop, it would take forever. So what are they doing under the hood? Anything that returns results in sublinear time, which means faster than if you wrote a for loop and had everything in memory. It's using one of two things. Like no matter what database you use, it's always boiling down to one of two things, and that's either a tree or a hash. So what that means is a tree just means you're dividing the data based on some criteria, and the criteria is set up in a way where if you're on sort of one side of the criteria, then your answer isn't on the other side. So for example, you could make a tree just based on the letters of someone's name. The tree could say, 'Is the first letter of someone's name less than or equal to M?' And if it is, you go one direction; if it's not, you go a different direction. So in this case, if I'm looking for Patrick, I say, okay, the first letter is a P. So I know that anything that's on the left side of the tree can't be Patrick. So I just focus on the right side of the tree.' And this is just assuming a binary tree. And so in this way you can actually search—you've effectively searched all of the entries, but you've just by making one decision, you've eliminated half of the entries. You just know that it's not any of those. And so there's B-trees, there's binary trees. Those are different. There's right—there's Red-Black Trees. Yeah, there's a bunch of different trees: there's R-trees, our star trees, there's vantage point trees. There's a ton of different trees, and they're all designed to eliminate options as quickly as possible, which should mean instead of searching a million entries, you're searching—you're searching five, right? Five plus making another six decisions. So you've gone from a million things you have to do to 11. And so this is how everything works when it comes to these kind of searches. Like if you're on Google Maps and you put in an address, you get it back right away. It's because there's some kind of tree underneath. Another way to do it is hashing, which is really just kind of a form of clustering. So for example, I might say, okay, let's take everyone whose name starts with a P and let's put them in one file or in one spot in memory, and everyone whose name starts with a J put in a different spot of memory. And so if someone's searching for Patrick, I know to look at the P file, and if someone's searching for Jason, I look at the J file. So it's not a tree; it's really just these buckets, but it does kind of the same thing. And so there's again there's a billion different ways to do hashing and clustering. There's actually some really interesting work with like Neural Networks and embeddings and clusterings that's relatively recent, and it's—it's like they're inventing new ways to do this all the time. But at the end of the day, it breaks down to one of those two things. So if you've ever tried to make your own Minecraft or done anything like that where you realize like, 'Hey, how am I storing all this in memory? It's impossible.' And how did they do it? Well, they're almost certainly using either a tree or a hash. Yeah.

  117. A

    And I think in the context of optimization what you should be asking yourself is if your code is running slow because you're trying to find something in a whole bunch of data, can you apply a tree or use hashing to eliminate the bulk of the data you need to search through more? Quickly. Yeah.

  118. B

    Exactly. And that gets into then doing kind of deferred computation and things like that. Like in the case of Minecraft, if you're not looking at something, then they can not process those chunks until someone's looking at it. And so there's a whole bunch of sort of dead reckoning type processes that go on.

  119. A

    Well, for other buzzwords you have like Binary Space Partitioning or things like that, which are also kind of a form of tree where you're dividing up a world into parts so that you can say if someone's looking forward, how do I eliminate everything that's behind them because I know they can't be looking at it?

  120. B

    Right now. Yep. Yeah, exactly. Binary Space Partitioning is literally a binary tree where every decision is a hyperplane. And so if you have a certain area, you say does that area cross the hyperplane? If it does, then I have to look at both directions. But if it doesn't cross the hyperplane—if the area you're looking at, like your frustum, is only on one side of the hyperplane, then you can skip everything on the other side. So yeah, there's indexing. Another thing is going beyond just running on one machine. There's distributed computing, which actually there is some one-machine distributed computing, like multi-threading, multi-processing, thread pools, things like that. So for example, let's say you have a huge list of items and you want to—a huge list of strings, and you want to capitalize all of them. I mean, this is very kind of a trivial example, but you could write a for loop and go from one to two billion, 'S = S dot uppercase,' right? But that's pretty slow. You could also say let me take my data and divide it into two batches—the one from zero to half a billion and from half a billion to a billion—and have two threads working on them. That's okay, but that has another issue, which is if for some crazy reason the first 500 million strings are very tiny and the next 500 million are huge, then the first thread will finish much quicker, and you'll just be waiting on the second thread forever. So you might say, 'Okay, I'm going to make a separate thread for every entry. I'm going to make a billion threads,' and you run that command, and you have to restart your computer because it's just caught on fire, right? So thread pools are a way to handle that. So you can give a thread pool a billion things to compute, and it will figure out the optimal number of threads depending on how sophisticated it is. But some thread pools will figure out the optimal number of threads like if you have 16 cores and hyper-threading, they'll say, 'Okay, you have 32 actual threads,' and it'll assign all 32 threads to 32 strings, and as they finish, it will assign more and more and more. So at any given time, you have 32 of these being processed, and you have a queue that could be huge. Eventually when the queue is exhausted, it'll tell you we're all done. So that's—that's a clear way to get some good benefit. I mean, there's obviously more complexity there, so you should only do it when you're working on code that takes a long time to execute. Another part beyond threading kind of taking it to the next level would be networking. So with threading, you're still limited by what your one computer can do. But you might say, 'Oh, I want to use a thousand computers. I want them all to be serving some website.' And so once you get into networking, then you get more into load balancing, which is similar to the way thread pool works. It's just kind of taking it to the networking level, and it requires a little bit more statistics because there's more uncertainty. But load balancing is effectively saying, 'Okay, I have 100 machines. Let me make sure all the machines are equally loaded.' So if one machine is serving one request, but that request is really expensive for some reason, then they'll give all the future requests to among the other machines, and load balancing it's similar. to thread pools except you're constantly having to sort of pull all the machines and find out if they're healthy or not. There's also other kind of networking tricks for optimization. There's Reliable UDP, which means typically when you do things over the internet, you do TCP. And that means the TCP protocol guarantees that I get every packet and I get it in order. So if I want to send Patrick an email, I want him to get every letter in that email, and I want him to get them in order. Like I don't want him to get this like weird jumble of letters. And so TCP seems very reasonable for that. But you may not need the in-order part. There are often times where you're just sending a bunch of data to someone, and you know, like let's say I'm sending a file to Patrick. He doesn't need to get all of the bytes in order; he just needs to get all the bytes and put them in the right place as he gets them. And so that's an example where I could use Reliable UDP and other kind of protocols to get a huge speed.

  121. A

    Up so I think about networking and the question is going to be when you have computers put together and you start to have an issue and you start looking at what—and when you get to networking level, you really have to be careful about collecting a lot of really good statistics so that you know there is a problem. Because often problems go undetected for a long time. I'm pretty tongue-tied tonight. And so for networking, one of the things like Jason was saying, you have a request comes in and it takes a long time, and you need to load balance. So what you would be looking for is what parameters should I be watching to see if I need to add a load balancer or change the algorithm my load balancer is using or add new computers? And so you would want to, for instance, look at what do the longest one percent of queries take, or 99 of queries take longer than this or that, or you know basically what is the histogram of response times?

  122. B

    Go ahead. Oh, as you say, if you ever hear the term P50 and P99, it's what Patrick's referring to. So P50 is what is the mean latency for something, and P99 is, you know, 99% of your requests have a latency less than that number, right?

  123. A

    So, so you might have when someone specifies how good a response time they want—they kind of often mean two things or three things. They want, you know, 99% of requests should complete within 10 milliseconds, but 100% of requests, or nearly 100%, should complete within one second. So I know that occasionally something will happen and I can't complete within 100 milliseconds, 10 whatever I said, but I never want a request to take too long. And so then that helps define how you would do load balancing, what architecture for your network you need. Um what do you do if, you know, 500 milliseconds has gone by? Should you like abort the request and start it again, and your remaining five, like how do you deliver on that? You know what you're trying to guarantee?

  124. B

    Yeah, and it gets really interesting once networking is involved. There was a case in a place I worked where it actually made sense to send the load balancer to requests every time. So in other words, like imagine that you need—you need some data, and you literally ask the same system for the same piece of data twice immediately one after another, and then you pick the one that returns first. And the idea is, you know, you have so many resources, but you can't control the latency, and so the only way you can do it is by making multiple calls at exactly the same time with exactly the same data and just picking the one that returns first.

  125. A

    But this is an interesting optimization. Before, you were talking about hashing, and so I guess when you go to distributed computer, the same optimization technique kind of becomes called partitioning, where you say some requests for certain usernames go to this computer, other usernames go to this other computer, right? And you partition the request, but you can if your partitioning scheme is complex or for various reasons, you may want the load balancer or the thing sitting out in front to issue requests to some or all of the computers behind it, and the first one who has an answer replies back. And then if the others don't ever end up or don't have the data necessary to respond, they just never respond.

  126. B

    Yeah, I mean you can do all sorts of interesting things. I mean the machine behind the load balancer could know that it's taking too long and give up on the assumption that the load balancer will pick someone else. And yeah, it gets—it gets pretty kind of math heavy, which again is a good reason to use off-the-shelf components for this. Don't try and write your own load balancer, but I think it's

  127. A

    also a really good reason to when you start designing a system understand what your goals are and also to try to make sure to collect really good data so that you can analyze problems when they come up.

  128. B

    Yeah, definitely. I mean we've talked about this in the past, but we can't stress enough how important it is to collect just a ton of data. You don't want to be in a position where you have some problem and you have to start collecting data to fix it. That's bad news. The last piece of this, you know, the top of the stack are just algorithmic improvements. So if you—you know if you haven't heard of this, there's this thing called Big O notation. It's just a fancy way of saying this is sort of the way that a particular algorithm grows in terms of computational, you know, computational time. So in other words, if something is N squared, then that means as the number of elements increases, increases the time it takes to get the answer you want goes up exponentially, right? If something's order N, then that means it scales linearly. So for example, if you want to loop through a list of strings and count the number of letters in the string in each string, and you assume that the strings are pretty small, you might say that oh, you know the length of the string doesn't really matter. This is order N in terms of the number of strings. As I add more strings that I have to count the letters of, you know, I increase linearly. If you're using as we said before like trees and hashing and things like that, you can actually do sublinear computations. So if you want to find for example, if you want to find the 10 real estate agents closest to you and you've put all of your real estate agents into an R-tree or an R* tree, now putting them into the R* tree that might take N squared, and that might take, you know, two days or something, right? Or N log N, I think is what it takes. But that might take a long time. But once you have that R* tree built, then you can look up, you know, the K nearest neighbors. You can look up the nearest realtors. in sublinear time. So even though there's 100 realtors, you only have to look at two to know that those two are the closest. And so, you know, whenever you start dealing with big values for N, you know when you're looking at, you know, a billion websites or, you know, a million strings, or what have you, that's where this Big O notation becomes really important because it will tell you kind of the best case and the worst case. I think Big O is is the worst case. There's also little o, and then there's like sigma o. Little o is the best case, and sigma o is the amortized cost. So for example, let's say you're building this tree and most of the time it takes logarithmic time, but every 10,000 times you have to do some big rebalancing that's expensive. That's where you would say it's sigma o of log N because you know you might have to pay a big hit, and you should kind of design your system around that, but it's rare. So yeah, all of these—all these different notations and algorithmic improvements—that's sort of a last-ditch effort like if you have gone through all these things and you realize you actually need a brand new algorithm and need to do some research, then that's that's another opportunity sort.

  129. A

    Of. I mean, I don't want to be particularly contradictory, and what you said at the end—if you need to invent some new algorithm, yes, probably last-ditch effort—but I think actually reducing algorithmic complexity is often your first step. You should approach which

  130. B

    is? Oh, that's true.

  131. A

    Storing if I'm storing all of my—if I'm searching for something and I'm just storing it in an array and binary search doesn't work because my array is not sorted, then you should say, 'Oh, maybe I should sort my array and use binary search,' or maybe I should use a tree, or maybe a Hash Map would be appropriate here. And the reason why I think that is kind of the first thing you should go to is because that code is still going to be pretty readable, and often pretty readable, and you'll end up not wasting your time trying to tweak your compiler only to find out that you need to switch to a different architecture and you lose all your gains. Those are going to be the most portable changes and can often lead to code that outstrips any other optimization you might be able to do.

  132. B

    Yeah, that's actually a really good point. So like, a couple of things: one thing is definitely use off-the-shelf algorithms. Like don't—don't really ever write your own sort or anything like that. But you're right. I mean, if you have sort of 10 elements, you might just use, you know, for loop and sort them really quickly and, you know, quickly in terms of effort. But then yeah, all of a sudden your requirements change and I have a thousand elements or 10 or a million elements. And then you're right. I mean, you could tweak the compiler all day long, but if your sort is, you know, the Bubble Sort that you wrote when you first started the project, then nothing is going to help you other than improving your algorithm. And I think

  133. A

    One of the things about optimization that's difficult is the—I don't ever know how comfortable I am feeling about referring to something as 'the art of.' But the art of optimization is knowing when not to optimize, yeah, or how much to optimize. And it's something that you can't often write down; you just kind of have to use judgment. But for instance, it may be that you have implemented Merge Sort because QuickSort—a good implementation of QuickSort isn't available on your system or whatever—and you're debating whether or not you should use it. You really should look at your use cases and say, 'Hey, it turns out I'm normally only sorting 100 items.' Though maybe it isn't; I don't know what the breakdown is. But often Merge Sort actually at the end does, or a QuickSort at the end does Merge Sort because it performs slightly better on small data sets, right? And so there's like some crossover point, right? But even if you didn't know that, if you're adding complexity or saying, 'Oh, I want to move to this very exotic binary tree because I think my binary tree might—you know, may not be exactly the best thing,' it's knowing when to invest that complexity and adding, you know, that to your code and potentially causing unintended consequences by having more complicated code than you did before, even if it does end up faster in some cases.

  134. B

    Yep. One last thing about algorithm improvements: a lot of what you'll do here isn't going to be inventing a new algorithm—maybe unless you're a professor or something—but it's actually going to be finding the right approximation. Like for example, if you have a list of numbers and they're streaming in—maybe it's, you know, you're building your own load balancer and you have a list of latencies that are coming through—you could store all of them, and now you can find the average latency and it's the P99 latency and P50, all of that, as we talked about. But that's a lot of numbers. I mean, you're getting maybe 100 of these a second. You don't want to keep this enormous list of latencies, right? So what you can do is approximate. You could—you maybe store the first 10,000 and then store some hyperparameters about, you know, all the ones you've seen up until now, or you could keep some kind of like distribution estimator, common filter, or something like that where you're not storing—you're storing two numbers and but you're just keeping those two numbers updated in some recursive way. And so, you know, especially as your application grows in size and popularity, what have you? A big part of it is figuring out, you know, where you can make approximations and what the trade-offs are.

  135. A

    Well, I think that's

  136. B

    A wrap. Yeah. So I promise—I promise I will get T-shirts or I will at least have sent myself a T-shirt that I'm happy with. You know, I'm going to do that before I subject anyone to buying a T-shirt that may not actually look good when you get it. But I promise I will have a T-shirt prototype by next show. And I think we're actually going to have an interview next show. It's not a guarantee, but it seems to be coming around that way. It's actually going to be really cool. I'm excited about this guest that we're going to have on the show. And yeah, if you have any questions—if you've had any like wicked, you know, optimization stories where like you fit, you know, the whole world in a Cheerio or something, that'd be awesome. Post on Facebook, post on reply to us on Twitter, and yeah, have fun, you guys. Yeah.

  137. A

    We need we get a fair amount of user feedback and emails, so thank you guys and gals for doing that. We should have more featured like emails that get written to us. We've had a lot.

  138. B

    Of really good ones. Yeah, maybe we'll do another mailbag or something or even just like

  139. A

    people. Yeah, like right, like we should give something for people to write in about and then we should like read the best ones. Like in this case, tell us your best optimization story, and then like we'll read it next time.

  140. B

    Yeah, that's true. That's true. If anyone has a cool optimization story, we'll definitely—we'll bring it up as our intro next time. All.

  141. A

    Right. Well, thank y'all.

  142. B

    Cool. See you later. The intro music is Axo by Binar Pilot. Programming Throwdown is distributed under a Creative Commons Attribution-ShareAlike 2.0 license. You're free to share, copy, distribute, transmit the work to remix, adapt the work, but you must provide an attribution to Patrick and I and ShareAlike in kind.