memcmp(data,data2,arraylen); 在大多数系统上,memcmp可能会很好地优化,它可能(在一些 平台上)被编译器内联。 ie #include< cstring> bool isequal(const char * a,const char * b,int len) { return :: memcmp(a,b,len)== 0; } 使用gcc:g ++ -mtune = i686 -O3生成: memcmp_tst.o:文件格式elf32-i386 部分的反汇编.text: 00000000< _Z7isequalPKcS0_i> : 0:55推%ebp 1:89 e5 mov%esp,%ebp 3:83 ec 0c sub Hey guys, my first post on here so I''ll just say "Hello everbody!"Ok heres my question for you lot.Is there a faster way to compare 1 byte array to another?This is my current code// Check for a matchmatch = true;for ( int i = 0; i < arraylen; i++){if( data[i] != data2[i] ){match = false;break;}}Thanks in advance guys!! 解决方案If the array is of a variable length, as in your above example, then I wouldsay that Yes, your code is pretty efficent, although maybe there''s somememory functions I''m unaware of that could do the job better?If the array is of constant length, I''d suggest the following:Struct ChocolateArray{int monkey[50];};int main(void){bool match;ChocolateArray aa;ChocolateArray bb;//Mess with the arraysif (aa == bb){match = true;}else{match = false;}}-JKopmemcmp( data, data2, arraylen );On most systems, memcmp may be nicely optimized, it may (on someplatforms) be inlined by the compiler.i.e.#include <cstring>bool isequal( const char * a, const char * b, int len ){return ::memcmp( a, b, len ) == 0;}using gcc: g++ -mtune=i686 -O3 generates:memcmp_tst.o: file format elf32-i386Disassembly of section .text:00000000 <_Z7isequalPKcS0_i>:0: 55 push %ebp1: 89 e5 mov %esp,%ebp3: 83 ec 0c sub 这篇关于字节数组比较 - 速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-01 15:42