什么是最好的或最快的方式来比较两个字符串? [英] What is the best or fastest way to compare two strings?

查看:112
本文介绍了什么是最好的或最快的方式来比较两个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道下面的代码有多快。如果有人知道比这更快/优化的代码,请让我知道。

I am not sure how fast the below code is. If anyone knows the faster/optimized code than this, please let me know.

int xstrcmp(char *s1, char *s2)
{
  while (*s1 == *s2++)
            if (*s1++ == 0)
                    return (0);
  return (*(const unsigned char *)s1 - *(const unsigned char *)(s2-1));
}


推荐答案

使用 :: strcmp 而不是您自己的手工滚动版本。您的编译器供应商很可能是一个仅装配版本,它使用特定于CPU的功能进行比较(例如,SSE4.2具有用于快速字符串比较的特殊指令)。MSVC版本是用汇编语言编写的,并且使用较大的比较而不是单个字符),特殊的套管未对齐的字符串的开始/结束(如果你有VS2010安装,它在 VC / crt / src / intel / strcmp.asm 。)

Use ::strcmp instead of your own hand-rolled version. Your compiler vendor has most likely an assembly-only version which uses CPU-specific features for comparison (SSE4.2 for instance has special instructions for fast string comparison.) The MSVC version is written in assembly for instance and uses larger compares (whole words instead of individual characters) as much as possible, special casing unaligned starts/ends of the string (if you have VS2010 installed, it's in VC/crt/src/intel/strcmp.asm.)

这篇关于什么是最好的或最快的方式来比较两个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆