C# equivalent to Delphi High() and Low() functions for arrays that maintains performance? -
in delphi there low() , high() functions return lowermost , uppermost index dimensions array. helps eliminate error prone for loops iterating array might fall victim insidious +1/-1 array boundary error, using <= when meant < terminating condition in for loop statement.
here's example low/high functions (in delphi):
for := low(ary) high(ary)
for i'm using simple for loop statement in c#:
for (int = 0; < ary.length; i++)
i know there array method getdimension(n) has own liabilities since introduce error accidentally using wrong dimension index. guess enumerators, worry there significant performance cost when scanning large array compared using for loop. there equivalent high/low in c#?
the c# equivalent intrinsic low(ary)
, high(ary)
functions are, respectively, 0
, ary.length-1
. that's because c# arrays 0 based. don't see reason why length
property of array should have performance characteristics differ delphi's high()
.
in terms of performance, big difference between pascal for
loop , used c derived languages concerns evaluation of termination test. consider classic pascal for
loop:
for := 0 getcount()-1 ....
with pascal for
loop, getcount()
evaluated once only, @ beginning of loop.
now consider equivalent in c derived language:
for (int i=0; i<getcount(); i++) ....
in loop, getcount()
evaluated every time round loop. in language c#, need local variable avoid calling function on , over.
int n = getcount(); (int i=0; i<n; i++) ....
in case of array, if optimiser ary.length
did not mutate during loop, code optimised compiler. not know whether or not c# optimiser that, please refer comments more information.
before start re-writing loops use local variables containing length of array, check whether or not makes difference. won't. difference between pascal , c-like loops outline above more significant in semantic terms performance.
the language particularly envious of d. here can use foreach
loop presents each item in array reference, , allows modify contents of array:
void incarray(int[] array, int increment) { foreach (ref e; array) { e += increment; } }
Comments
Post a Comment