for() vs foreach()
#8

This is based on the assumption that both loop methods are to be used for players, when in reality they can be used for a lot of purposes.

Quick Analysis:
In general, foreach vs. for is simply a memory vs. time argument.

foreach creates an extra array behind the scenes (a linked list), the loop will loop n times (n = "Current Number of Players": dynamic). It does 1 check per iteration, this check uses data within the Pawn script.

for does not create an extra array, however it will ALWAYS loop n times (n = "Max Players": constant).. It does a constant 2 checks per iteration. One of the checks involves a call to a native function rather than a 'pure' value check of data already inside the Pawn script.

Summary:
  • foreach is faster, uses more memory and is easier to use.
  • for is slower, uses less memory but is more difficult to use.
Conclusion:
The extra memory used in foreach is generally taken advantage of multiple times due to the amount of times a "player loop" is usually required by a script. For this reason it's recommended to use foreach in general purposes, the extra memory is insignificant to most servers.
Reply


Messages In This Thread
for() vs foreach() - by The Scripter - 20.08.2010, 22:04
Re: for() vs foreach() - by Vince - 20.08.2010, 22:29
Re: for() vs foreach() - by CaHbKo - 20.08.2010, 22:31
Re: for() vs foreach() - by Carlton - 20.08.2010, 22:56
Re: for() vs foreach() - by Nero_3D - 20.08.2010, 23:24
Re: for() vs foreach() - by The Scripter - 20.08.2010, 23:32
Re: for() vs foreach() - by [L3th4l] - 20.08.2010, 23:35
Re: for() vs foreach() - by Simon - 20.08.2010, 23:51
Re: for() vs foreach() - by The Scripter - 20.08.2010, 23:58
Re: for() vs foreach() - by lolumadd - 21.08.2010, 00:04

Forum Jump:


Users browsing this thread: 2 Guest(s)