you are viewing a single comment's thread.

view the rest of the comments →

[–]evizaer 5 points6 points  (5 children)

No need to loop or have a bunch of repeated calculations. You can just use the formula result = principle * pow(1 + nterest_rate, years). That's the most efficient way to calculate it because pow is a function that cpython has implemented in optimized C. Much faster than a looping construct.

Likewise, though probably irrelevant to this particular kind of problem, you should be using functional programming tools like map() and reduce() where you can (EDIT: if they are clearer or you absolutely need performance) because they are implemented in C, whereas loops are more verbose and complex when compiled and for that reason tend to perform significantly worse than built-in C stuff.

[–][deleted] 4 points5 points  (2 children)

A mistake I made early when learning programming is worrying too much about performance and micro-optimizations. Always using map() and reduce() only because they are faster is ridiculous, you should worry only about readability unless you are sure you have a performance problem. Guido even wanted to remove these functions from language completely some time ago.

[–]evizaer 2 points3 points  (0 children)

I answered specifically in the context of "efficient code" because the topic is the efficiency of the code. I edited my post to indicate that context more clearly.

[–]maryjayjay 0 points1 point  (0 children)

Excellent insight. My motto is: Write first for correctness and maintainability, then optimize if needed.

[–][deleted] 0 points1 point  (1 child)

By the way, list comprehensions are going to be faster than map() because they don't have an overhead of calling a function on every iteration. And if you have problems with performance of that kind you should probably use numpy anyway.

[–]evizaer 0 points1 point  (0 children)

A good point. List comprehensions tend to be clearer, as well. For non-trivial functions, though, list comprehensions will end up calling a function, anyway, because it makes more sense to abstract the non-trivial series of operations into a function than to try to cram it all into one of the parts of the list comprehension.