| |

VerySource

 Forgot password?
 Register
Search
View: 9|Reply: 4

How to compare two byte arrays in .net with the most efficient

[Copy link]

1

Threads

2

Posts

3

Credits

Newbie

Rank: 1

Credits
3

 China

Post time: 2020-3-24 01:30:02
| Show all posts |Read mode
How to compare two byte arrays in .net with the most efficient
Reply

Use magic Report

0

Threads

3

Posts

4

Credits

Newbie

Rank: 1

Credits
4

 Singapore

Post time: 2020-7-14 11:30:01
| Show all posts
Compare the lengths first. If it is the same, do you compare each element directly? If it is different, return.
Reply

Use magic Report

0

Threads

95

Posts

56

Credits

Newbie

Rank: 1

Credits
56

 China

Post time: 2020-7-14 14:45:01
| Show all posts
for example;

static bool ByteEquals(byte[] b1, byte[] b2)
        {
            if (b1 == null || b2 == null) return false;
            if (b1.Length != b2.Length) return false;
            for (int i = 0; i <b1.Length; i++)
                if (b1[i] != b2[i])
                    return false;
            return true;
        }
Reply

Use magic Report

1

Threads

2

Posts

3

Credits

Newbie

Rank: 1

Credits
3

 China

 Author| Post time: 2020-7-17 06:45:01
| Show all posts
I remember that there seems to be an instruction in .net that compares the data in two memory areas. I mean that
Reply

Use magic Report

0

Threads

2

Posts

3

Credits

Newbie

Rank: 1

Credits
3

 China

Post time: 2020-7-17 19:15:01
| Show all posts
There is basically no algorithm to optimize
However, you can use the following two methods to deal with, and you can get some efficiency improvement.
1. Use stack-based arrays
byte* byteArray= stackalloc byte[10];
Because stack-based arrays do not check for overflow, better performance can be obtained, and because they are used on the stack, there is no memory release problem, and no garbage collection is required.
2. Use pointers
fixed (byte* p1 =&b1[0])
In this way, you can directly use the pointer ++ to process without checking the array boundary. Second, the garbage collection will not move the array
But the above two methods need to be compiled by /Unsafe
Reply

Use magic Report

You have to log in before you can reply Login | Register

Points Rules

Contact us|Archive|Mobile|CopyRight © 2008-2020|verysource.com ( 京ICP备17048824号-1 )

Quick Reply To Top Return to the list