4

Hi I got following code in C# unsafe where array is fixed

array[(int)(index)]

index is long (and has to be long for some reasons).. so I need to cast it to int in order to get access to array element. Is there a way to use pointers or some other combination of actions in unsafe code to prevent this cast cause index can have long value of 1 for example (and never exceeds int value obv).. I feel that maybe unsafe pointers addition could prevent it from happening. I also feel this cast is not for free..and performance is the issue here. (exactly this line) I also think its not possible but I ask just in case im mistaken.

Ok ill give some more detail , im doing some required logical operations on long preIndex like

value = array[(int)((preIndex & mask ) >> 10)]

those operations are required and code is fairly minimalistic already. Only thing I can find to be optimizable is this cast from long to int, cause bitwise operations are required.

Thanks

2
  • 2
    A cast from long to int is insanely fast - what makes you think that this is a performance issue? Jan 20, 2011 at 10:05
  • Wow actually fun part is , I removed this (int) explicit cast leaving it implicit and performance dropped by 18% O_o I guess ill keep (int) even in unchecked context.. =) Jan 20, 2011 at 10:36

5 Answers 5

3

In unchecked context (the default), the cast will just discard the unneeded MSBs, so there isn't a performance penalty. In checked context, it will throw an exception if the index range exceeds int.MaxValue.

6
  • so your saying this cast to int has no performance impact at all? Jan 20, 2011 at 10:05
  • 2
    Yes, in unchecked context. So you may want to wrap it into unchecked((int)index) Jan 20, 2011 at 10:08
  • im already in unchecked context however is there a link with proof for this? it simply sounds unreal.. Jan 20, 2011 at 10:10
  • 1
    You should be able to prove it by decompiling the code. Let me try. Jan 20, 2011 at 10:13
  • 1
    @Valentin - this should be the difference between conv.i4 and conv.ovf.i4 Jan 20, 2011 at 10:15
2

Yes there is a trivial cost converting from long to int, but I'm very sure that a: it won't matter in any sane code and b: it is unavoidable (arrays are accessed via int index; period). To show the won't matter:

static class Program
{
    static int GetSize() { return 10000; }
    static void Main() {

        int size = GetSize();
        int[] someData = new int[size];

        var watchInt32 = Stopwatch.StartNew();
        for (int i = 0; i < 5000; i++)
        {
            for (int j = 0; j < size; j++)
            {
                someData[j]++;
            }
        }
        for (int j = 0; j < size; j++) someData[j] = 0;
        watchInt32.Stop();
        long lSize = size;
        var watchInt64 = Stopwatch.StartNew();
        for (int i = 0; i < 5000; i++)
        {
            for (long j = 0; j < lSize; j++)
            {
                someData[j]++;
            }
        }
        watchInt64.Stop();

        Console.WriteLine("{0}ms vs {1}ms over {2} iterations",
            (int)watchInt32.ElapsedMilliseconds,
            (int)watchInt64.ElapsedMilliseconds, 5000 * size);
    }
}

I get:

162ms vs 215ms over 50000000 iterations

So unless your code does nothing except array access, this just isn't going to matter. At all. In any significant way.

6
  • thanks for the reply, but replace 5000 with 1000 billions and youll see difference I think. My code does 160 million operations per seconds and has to run for days. Jan 20, 2011 at 10:14
  • I guess your right and its unevoidable , I think so too. I was just hoping for some magic way to ignore left bytes maybe or something, guess there is none. Jan 20, 2011 at 10:17
  • You could perhaps try a union struct, but I expect that would be slower; tested: 155ms vs 245ms vs 316ms over 50000000 iterations Jan 20, 2011 at 10:19
  • im not sure what you mean by union struct? just out of curiousity now, since its slower anyway ;) Jan 20, 2011 at 10:24
  • @Valentin my point is; surely it does something else than just get/set array values by index; in most cases that something will completely dwarf array access (which is, to stress, very very very cheap) Jan 20, 2011 at 10:25
1

I don't think you have to worry about a possible performance impact due to the conversion. Just look at the machine code generated by the JIT, they are identical for both the int and the long index:

x86, release mode, int index:

        var val = arr[idx];
00000059  cmp         ebx,dword ptr [edx+4] 
0000005c  jae         00000078 
0000005e  mov         esi,dword ptr [edx+ebx*4+8] 


x86, release mode, casted long index:

        var val = arr[(int)idx];
0000005f  cmp         ebx,dword ptr [edx+4] 
00000062  jae         00000081 
00000064  mov         esi,dword ptr [edx+ebx*4+8]

x64, release mode, int index:

        var val = arr[idx];
00000060  movsxd      rcx,ebx 
00000063  mov         rax,qword ptr [rdi+8] 
00000067  cmp         rcx,3 
0000006b  jae         0000000000000080 
0000006d  mov         ecx,dword ptr [rdi+rcx*4+10h] 


x64, release mode, long index:

        var val = arr[(int)idx];
00000061  movsxd      rcx,ebx 
00000064  mov         rax,qword ptr [rdi+8] 
00000068  cmp         rcx,3 
0000006c  jae         0000000000000080 
0000006e  mov         ecx,dword ptr [rdi+rcx*4+10h]

As Daniel Gehriger pointed out, the conv.i4 IL instruction doesn't need to be considered in the machine code, the 32 MSBs are simply dropped.

2
  • How would you comment the fact that when I remove (int) casts and leave them implicit performance drops from 110 million operations per second to 90 million? I removed 16 (int) casts inside my loop. This is very interesting though that machine code is the same, if it is the same , how comes there is a performance drop which you can see in answer I marked as answer for longs being cast to int? Jan 20, 2011 at 19:39
  • Interesting question; have you looked at the disassembly (of your code)?
    – Frank
    Jan 20, 2011 at 19:55
-1
int count = 10000000;
            object [] a = new object[count];

            Stopwatch s1 = Stopwatch.StartNew();
            for (long i = 0; i < count; i++)
                a[i] = new object();
            s1.Stop();

            Stopwatch s2 = Stopwatch.StartNew();
            for (int i = 0; i < count; i++)
                a[i] = new object();
            s2.Stop();       



            Debug.WriteLine(s1.ElapsedTicks + "  " + s2.ElapsedTicks);

3362502 3115428

So there is no significant impact.

2
  • interesting how you say theres no impact, while first version runs at least 7% slower ;) Jan 20, 2011 at 10:26
  • Because if you switch their places - the result will also vary :). But you are right, a little of it should be considered. Jan 20, 2011 at 10:28
-1

The performance issue you see from that line is from the index lookup - is it a regular array, like object[] ? or did you implement the index property?

5
  • 3
    For your information, a dictionary lookup is way slower than a index lookup in an array. Jan 20, 2011 at 10:06
  • its basic fixed (int* array= safeArray[0]) without anything special Jan 20, 2011 at 10:06
  • @Øyvind: I might have been a bit fast on my answer - there is no doubt that index lookup is faster. I thought that the indexer maybe was on some class that implemented it - since that was stated as beeing slow(er) - it's not like there was a lot of context for this question :) If it is normal array access there is not a lot to be done. To optimize I would maybe look at loop unrolling or even the mono runtime with SIMD support if it's appropriate for the problem. Jan 20, 2011 at 12:13
  • No problem. Just wanted to comment so other don't get confused here :) (for the record, the downvote is not by me) Jan 20, 2011 at 12:21
  • @Øyvind: Fair enough - I removed the bad suggestion :) Jan 20, 2011 at 12:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.