Makes sense, but I never thought of this before! If you're only doing the myvector.size() for one operation, say if the loop only went once, would it be more efficient?
If you like making fast programs (I know I do!) one thing to consider (that is often overlooked) is looping.
I'm not saying looping is slow, in cases it's needed, but take this code for example (C++):
Notice where in the loop, you are calculating the size. In a looping structure such as this, the computer will be calculating the terminating condition (in this case i < myvector.size() ) every time the loop iterates. Though not major with smaller lists, in programs where you have a large list to process (that doesn't get modified as the loop is running), this can quickly add up.Code:vector<string> myvector; // .... for(int i = 0; i < myvector.size(); i++){ // do stuff... }
More calculations = less speed = more space needed to store the calculation = more heat generated inside the computer = CAN SUCK MAJORLY
Easy way to speed up, save space, the environment, etc: create a variable to hold the size. In most languages depending on the structure a size() or count() operation can cost O(n), and running something that slow many times as you iterate through a list sucks.
Code:vector<string> myvector; // .... int vsize = myvector.size(); for(int i = 0; i < vsize; i++){ // do stuff... }
Makes sense, but I never thought of this before! If you're only doing the myvector.size() for one operation, say if the loop only went once, would it be more efficient?
It'd be roughly the same time considering it's doing the exact same number of calculations. I mean, the time it takes the compiler to declare and set an additional variable is barely measurable.
Also, not a bad tip, but I'm fairly confident that some modern languages are actually smart enough to take care of this for you.
I don't think it would be that much of an improvement. Both ways of doing the loop would be O(n) efficiency. Sure it'll be slightly faster, but it would probably be unnoticeable. Also this would not apply if the size() thing changed values. And jeez, C++ looks so similar to Java :o
Hmm, I don't see it in your post but okay :p
But I guess your tip is somewhat useful as it can reduce something that could take 2n steps to n+1.
By the way, are you in college or high school? I thought you were older but your thread about physics made me consider otherwise :o
Collegemost physics courses are taken sophomore year at my school and I'm already in 4th-year CS courses
Cool, I'm still in high school lol. Taking Java course as a junior and going to take C as a senior
CS is probably going to be my major :p
Yeah my HS didn't teach anything even related to computers, self-taught myself a lot