r/programming • • May 25 '19

Making the obvious code fast

https://jackmott.github.io/programming/2016/07/22/making-obvious-fast.html
1.3k Upvotes

263 comments sorted by

View all comments

-8

u/Beaverman May 25 '19

I don't understand linq and streams. What's wrong with the imperative for loop? How is it any easier to read than a for loop and a variable?

Linq and streams are not how the computer executes your code, it's not how you'd write the math. What's the point?

0

u/[deleted] May 25 '19

[deleted]

-8

u/Beaverman May 25 '19

You're ignoring half the paragraph in order to spew the most obvious and cliche point in modern software development.

The question was: What's the point. The part you are quoting is an observation that the functional style is no closer to the actual execution, and therefore that could not be the point. The second part (that you didn't quote) is the same observation about mathematics. I've never seen a mathematician talk about aggregating something with the function that takes two arguments and returns the addition of the two.

I'm not "intimidated" by functional programming. I've tried it. I've written Haskell, I've written Scheme. I've written functional Lua, and used Java streams. I think that functional languages, like Scheme Haskell (and to some extent lua and python) have interesting ideas that are useful in certain contexts. I don't think those ideas have any business being used in the way they are. .Aggregate is not more clear than a simple for loop.

PS: If you want to hear the second most cliche opinion in software development: I don't think OOP is any good either. Understanding what the computer is going to do is of utmost importance, because there is really only one thing that matters: Does the code work. The code that doesn't execute doesn't need to be maintained.

6

u/ylyn May 25 '19

In some (many) situations, functional/declarative style is actually clearer and easier to reason about.

At least to me. YMMV.

0

u/Beaverman May 25 '19

In which cases? Do you have any examples?

0

u/[deleted] May 26 '19

[deleted]

2

u/Beaverman May 26 '19

I wouldn't read too much into the performance difference of the tests. whichever one runs first is probably including the runtime startup and jit time in the results. I can't quite believe you'd be able to observe a difference in this short of an execution (you're probably not hitting a GC in either example).

As for the readability of you example, i think it's a great case. A case like you have here is where streams are the closest to making sense. The case is also pretty simple, making the syntax and mental overhead of the nesting scopes minimal. Streams don't get really problematic until you have something like:

var y = getRelated();
foo.stream().map(x -> {
    if(y.processFoo(x))
        return x;
    return null;
});

Which some of the code i maintain looks like. I still have people telling me that "streams are more readable", even when we have shit like this in the codebase.

Even then, I still firmly believe the imperative example shown here is just better, because it's much more clear in its description of what the computer will do.

As for the negative reception, there's probably some amount of people who just don't agree, and it sucks that i get downvoted for that. There's probably also some amount who take offense with the argumentative (and sometimes hostile) way I've deliberately written some of the responses. I chose this style of argument because it makes it clear that i don't think people who like streams prefer a different "style" to me, i think they are wrong. People who like FP prefer a different style to me, people who like streams are just wrong.

0

u/[deleted] May 25 '19

[deleted]

-3

u/Beaverman May 25 '19

If you think functional programming is somehow less mathematical

I don't think functional programming is less mathematical. Functional programming is very mathematical. What is not mathematical is the particular favor of "functional" goop called Linq and Streams. Have you ever seen a mathematical paper talk about anything that looked like Linq and Streams?

I don't dislike Haskell and Scheme. In fact a like them. I hope we got that out of the way.

I hope I never have to share and maintain a codebase with you.

I don't think you'll have that problem, seeing as you'll probably never have a codebase worth maintaining. (I know that's pretty snarky, but you have to respond to snark with snark).

0

u/[deleted] May 25 '19

[deleted]

1

u/Beaverman May 25 '19

How is it more explicit? It's way more explicit to just do the thing you want to do.

Yes, they are higher level. That doesn't make them good.

In each case, the benefits for the writer of the code include reliability (no off-by-one errors with indices and such)

That's solved by for-each loops. They are pretty simple in their function, and easily understandable.

brevity (lack of boilerplate).

How is doing what you actually want to do boilerplate? If what you want to do is sum a set of numbers, then why not just sum those numbers?

0

u/[deleted] May 25 '19

[deleted]

2

u/Beaverman May 25 '19

To be more specific, the intent (the what) is more explicit, not the method (the how).

That's what i understand "more high-level" to mean. It's also commonly refereed to as declarative. I've never heard it called "more explicit", because the entire point is to hide details.

For example, a LINQ where clause or the typical [...]

But what you are trying to do with a piece of code is very rarely to "filter" some list. What you are trying to do is something domain specific, like "find all the apples". So you still have to try and decipher what the code actually does.

In my example we might have something like

fruits.filter(x => x.type == APPLE)

It's not obvious what the purpose here is, all you've done is put the if you'd otherwise have in the loop in some strange function pointer. and at the same time you've made hand optimizing it impossible and any higher level reasoning about code flow is not also harder. It becomes much worse if you start calling other methods inside that lambda, since that messes with the flow completely.

You can implement this in two ways yourself, either you use a decorator, so an object that wraps the enumerable and selects only apples, which is pretty simple, and probably what linq does anyway.

if(fruit.type == APPLE)
    return fruit;
return null;

The other alternative is to just do it eagerly

foreach(auto fruit in fruits) {
    if(fruit.type == APPLE)
        apple.add(fruit);
}

That's pretty simple, and they say about as much about the problem as the filter does, but they also clearly show the runtime performance implications.

As for the "boilerplate", I'd say that all example here don't contain any boilerplate. Your problem literally is "walk through the list and select all the fruits that are apples. Or maybe "only return apples from the iterable". It's not boilerplate if it's literally your logic. It's just code.

6

u/mrjackspade May 25 '19

Using a for loop is fine for something like a sum, but Linq is significantly easier to write and maintain when dealing with more complex generic functions, or chaining things together. Being able to define a Where filter implementation for an unknown iqueriable provider of an unknown underlying set type and call it with ~4 lines of code is a godsend, and being able to use Linq to chain together function calls for generic sets based on parameters is significantly more readable than writing a 500 line block of "if" statements.

When you're dealing with Linq you're talking about a lot more than just the syntax. It's an access system for dealing with IQueriables, IEnumerables, ICollections, etc, and interacting with those in an intuitive way using expression trees/delegates/etc.

If you don't understand the benefit it's likely just because you haven't written code yet that would see a benefit to using it.

2

u/Beaverman May 25 '19

Do you have a real world example we could discuss? That might be easier to talk meaningfully about instead of hypotheticals. I sums because it has examples directly in OP.

What sort of problems are you solving where you need to query unknown shit in unknown ways? Do you think you might have overgeneralized and overcomplicated the problem in some way?

But does it make sense to combine enumerables and queryables? Is accessing a list the same thing as accessing sets in a database? I'd say no.

2

u/accidentalginger May 26 '19

One advantage is that you abstract the manner in how the data is filtered and transformed. This is useful when dealing with multiple sources of the same type of data. For example, in blended levels of cached data (local RAM, memcached/redis, and a backing database), the extension methods of LINQ can be materialized as execution plans for the remote data sources which optimizes access. For example, the database query can be created from the expression tree so you don’t have to write custom queries for every database call, nor do you need to read in useless data. You can go from three different iteration algorithms for each level of the cache to one expression that can be used optimally for each source.

2

u/Beaverman May 26 '19

But those things are not the same. Filtering a list in memory doesn't have the same failure mode as a remote db call, they don't have the same performance. They just are not equivalent. There's plenty of cases where a Linq query won't "materialize" into anything you actually want.

Don't get me wrong, high level tools like JOOQ can make sense, but unifying them across database and memory levels is just not a good idea.

Writing the SQL queries is way easier than trying to reason about what comes out of Linq, especially if you use the same expression for in memory and database access. Writing a few SQL queries just isn't that hard.

2

u/accidentalginger May 26 '19

Clearly yes, the different sources have different performance characteristics, execution plans, etc. That’s the point of having caching in the first place. What LINQ provides is a high-level abstraction so that your code is clearer to interpret. C# does not really support higher kinded types generally, but LINQ does provide some aspect of that with respect to certain collection generics. Writing SQL by hand can be faster. Writing the query directly for the caching service can be faster. But the compiler support for LINQ, as well as a well-tuned evaluator for the expression trees (likely with its own memoization) lends to nearly if not perfectly comparable performance to these hand-tuned solutions, with the additional benefit of highly readable code.

1

u/Beaverman May 26 '19

But you code is not "clearer to interpret". the line between "fast" and "so horribly slow that it won't even compute" is razor thing when doing Linq on a database. Some operations compile to single SQL queries, others require loading all the data into memory. That's not clearer in any meaningful sense of the word.

For my argument to make sense to you, you will have to adopt a view where the idea of a language translating into SQL is separate from a language that works across datastores. This is not an argument against object mappers (I have other arguments against them), it's an argument against an objectmapper that tries to treat all datastores as the same.

A database is good at different things when compared to a list. Therefore they require different API's.

2

u/accidentalginger May 27 '19

For my argument to make sense to you, you will have to adopt a view where the idea of a language translating into SQL is separate from a language that works across datastores.

You seem stuck in the idea that you and you alone can be the only one that is right. I’ve been in all roles of an engineering function, from junior to principal to management to founder. You’re missing the largest cost of an engineering practice: headcount. I’m going to take an educated guess and say you’re probably a senior or principal engineer, judging by your specific arguments. I’ll reformulate my approach.

Hand optimized will almost always be faster, whether it’s to replace the duties of an ORM, a multi-tiered cache, or even pure algorithms. You can regress this argument infinitely, however, to the point of justifying writing assembly or offloading to FPGAs or ASICs. Here’s the thing: these are optimizations to bottlenecks. They suck as general solutions. If you have a crazy query built off of joining five different tables from two separate databases with specific ordering and query criteria, yeah, LINQ to SQL or Entity Framework or NHibernate or anything else out there will totally shit the bed. At that point, you would need to optimize. But stored procedures are supported by these frameworks, and you can still leverage the strengths of the abstraction to provide greater clarity. Clarity is key here. Developers are expensive, and spending 80 hours to write the most optimal SQL for every situation is insane to justify for businesses that are small or have rapidly shifting requirements — and ensuring that the other engineers can even quickly understand that optimization is also expensive, either because the headcount is staffed by mythical 10Xers that can quickly grok it, or because the amount of effort spent in understanding it took 10 times as long. Companies with billions in their coffers can afford that, but even they lose velocity, which harms the competitive angle. Or, instead of being another victim to the vice of premature optimization, you can have a cleanly abstracted DAL that still lets you leverage the use of LINQ across multiple data sources without sacrificing perf because the specific places where perf is being damaged by the AST compiler can be mitigated with hand optimization for those calls.

Bottom line: LINQ enhances readability generally more than hand optimized code. Readability matters more often than slight performance gains, and performance gains can be made by optimizing where needed.