I’m just curious about which is the most efficient way of doing this kind of node enumiration:
for i in something():
o=[var1,var2,var3,varN][i]
o.new()
o.do_something_based_on_number_of_loops()
add_child(o)
or
for i in something():
match i:
0:
o=var1
o.new()
o.do_something_based_on_number_of_loops()
add_child(o)
1:
o=var2
o.new()
o.do_something_based_on_number_of_loops()
add_child(o)
2:
o=var3
o.new()
o.do_something_based_on_number_of_loops()
add_child(o)
N-1:
o=varN
o.new()
o.do_something_based_on_number_of_loops()
add_child(o)
or
var items = [var1,var2,var3,varN]
for i in something():
o=items[i]
o.new()
o.do_something_based_on_number_of_loops()
add_child(o)
Or is there a more efficient way of doing it?
Edit: Sorry if that wasn’t clear. Is it better to constantly get something from an “unstored list”, store the list in a variable, or not use a list and use a match statement instead? Do they have any advantages/disadvantages that make them better in certain situations?
Rule #1 of programming: Write good code first, then measure performance.
Premature optimization is the root of all evil.
Rule number 2: stop dismissing performance questions just because of something some guy said decades ago. Performance matters, learning about performance matters, and answers like yours dont help anyone.
Did they ask if they should optimize, or did they ask which one generates more performant assembly? Which one of those questions did you answer?
Maybe they already measured and already knows this is a bottleneck. Maybe they are curious if match statements are a slow abstraction (e.g. in python, it’s essentially a chain of if/else. In rust it’s often compiled to an indexable table). Maybe the given example code is only partially representative of the actual code this is being applied to.
It’s so irritating to look up performance-related questions when this answer is at the top (and middle, and bottom) of every thread. I swear half the reason every piece of modern software runs like shit is because nobody bothered to learn how to optimize and now everyone just parrots that phrase instead of saying “i dont know”.
There’s tons of little “premature” optimizations that you can do that arent evil. Choosing the right data structure (how random is the access? Are you using keys? Does it need to be sorted?). Estimating time complexity and load size (e.g. “i’m parsing [11 million | 2] files, i should probably [keep time complexity in mind | ignore time complexity completely]”). Structuring loops in a way that’s easy for compilers to auto-vectorize - usually it’s not any harder to read what the loop is doing, so why not do it right away?
Yes i’m bitter =(