Author Topic: Don't think. Profile.  (Read 3138 times)

Offline chaos

  • BFF
  • ***
  • Posts: 291
  • Job, school, social life, sleep. Pick 2.5.
    • View Profile
    • Lost Souls
Don't think. Profile.
« on: December 22, 2008, 01:16:11 AM »
So a while back, I started preferring this old-school inventory loop form:

Code: [Select]
for(object obj = first_inventory(whatever); obj; obj = next_inventory(env))

over the modern

Code: [Select]
foreach(object obj : all_inventory(whatever))

because, eyeballing it, I thought that the former would be faster because next_inventory() is a simple linked-list next-item link, doing a foreach() on all_inventory() makes the driver build a temporary array that it's just going to throw out, and so on.

For whatever reason, I just got around to actually testing this out, and discovered that the foreach() is about 17% faster.  Why, I can't imagine, but that's how it is.

Moral of the story: don't think, profile.

Offline Jimorie

  • Friend
  • **
  • Posts: 58
    • View Profile
Re: Don't think. Profile.
« Reply #1 on: March 11, 2009, 12:54:39 PM »
Just throwing my uneducated guess in here.

It is fairly clear that the n extra function calls to next_inventory() is responsible for the overhead you see. Function calls do have a non-trivial cost just by themselves. Disregarding whether the function is very cheap itself, it still requires the necessary stack operations.

You don't get any of that when going through an array.