C++ 中短字符串的快速算法

如果我们在实际工程中,碰到的字符串都是小于8个字节的短字符串,我们可以通过以下的方法优化来提升系统的性能

就是将字符串pack到一个64位整数里。

下面的算法将短字符串转换为一个整数

inline  void  convert( const   string   &  buf, uint64  &  n) 

     n 
= 0
     
int length = buf.length(); 
     
for(int i = 0; i < length; ++i) 
     

          n 
= (n << 8+ (uint64)(buf[i]); 
     }
 
}

我们在此基础上实现一个查找算法

class  ShortString 

public
     ShortString(
const string & buf) 
     

          convert(buf,m_str); 
     }
 
 
     
bool find(const uint64 & nsub, const int num) 
     

          uint64 n; 
          uint64 mask 
= 0
          
for(int i = 0; i < num; ++i) 
          

               mask 
= (mask << 8+ 0xFF
          }
 
          
for(int i = 0; i < 8++i) 
          

               n 
= (m_str >> (8 * i)); 
               
if(n < nsub) break
               n 
= (n & mask); 
               
if(n == nsub) return true
          }
 
          
return false
     }
 
 
private
 
private
     uint64 m_str; 
}
;

测试函数如下

int  main()

     
string buf = "abcdefgh";
     ShortString shortstr(buf);
     
string sub = "cddg"
     uint64 nsub; 
     convert(sub,nsub);
     time_t begin_time,end_time; 
 
     
if(shortstr.find(nsub,4)) cout << "ok" << endl;
 
     begin_time 
= clock (); 
     
for(int i = 0; i < 10000000++i)
     

          
if(shortstr.find(nsub,4)); 
     }
                                                                                                                                                  
     end_time 
= clock ();
     cout 
<< end_time - begin_time << endl;
 
     begin_time 
= clock ();
     
for(int i = 0; i < 10000000++i)
     

          
if(buf.find(sub));
     }

     end_time 
= clock ();
     cout 
<< end_time - begin_time << endl;
 
     
return 0
}
 


根据测试,这个方法比普通的快4倍左右
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值