SDS的概念
SDS:
保存了len和free属性,并保存了字节数组,同时以‘\0’结尾。
可以在改变字符串长度的时候,减少内存的分配次数,提高性能。
并且可以重用一部分c中的String Api.
- free属性为0,表示这个SDS没有未使用的空间。
- len的属性为5,表示这个SDS保存了5字节长的字符串。
- buf是一个char类型的数组,最后一个位置保存了’\0’(为了复用语言的api)。
JAVA实现
注:因为java中的String不需要以’\0’结尾,所以实现的时候没有存’\0’。
核心代码
/**
* 简单动态字符串SDS
* - 字节数组存储
* - 记录已经使用的空间
* - 保存还剩余的空间
*/
public class SDS {
//记录buf数组中已经使用的字节数量
int len;
//剩余的空间
int free;
//保存字符串
char buf[];
@Override
public String toString() {
return len > 0 ? new String(buf,0,len) : "";
}
//打印SDS信息
public void printDetail(){
System.out.println("========================");
System.out.println(" len is "+this.len);
System.out.println(" free is "+this.free);
System.out.println(" buf is "+Arrays.toString(buf));
}
public int length(){
return this.len;
}
public SDS(String msg){
buf = msg.toCharArray();
len = msg.length();
free = 0;
}
//更新
public void update(String msg){
if(this.buf.length > msg.length()){
System.arraycopy(msg.toCharArray(),0,this.buf,0,msg.length());
len = msg.length();
free = buf.length - len;
}else {
buf = msg.toCharArray();
len = msg.length();
free = 0;
}
}
public SDS(){
buf = new char[50];
this.len = 0;
this.free = buf.length;
}
//拼接操作
public void add(SDS sds){
if(this.free >= sds.len){
System.arraycopy(sds.buf,0,this.buf,this.len,sds.len);
this.len += sds.len;
this.free = this.buf.length - this.len;
}else {
char [] newCharArray = new char[this.len+sds.len+50];
//先复制this
System.arraycopy(this.buf,0,newCharArray,0,this.len);
//再复制add
System.arraycopy(sds.buf,0,newCharArray,this.len,sds.len);
this.len += sds.len;
this.free = newCharArray.length - this.len;
this.buf = newCharArray;
}
}
}
测试
public class SDSTest {
public static void main(String[] args) {
//新建一个SDS
SDS sds = new SDS();
sds.printDetail();
//使用String构造一个SDS
SDS hello = new SDS("hello");
hello.printDetail();
//更新sds
sds.update("fuck");
sds.printDetail();
//拼接sds
sds.add(hello);
sds.printDetail();
//直接输出sds,因为重写了toString 方法,所以看不出异同
System.out.println("=====>");
System.out.println(sds);
}
}
测试结果:
========================
len is 0
free is 50
buf is [ , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ]
========================
len is 5
free is 0
buf is [h, e, l, l, o]
========================
len is 4
free is 46
buf is [f, u, c, k, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ]
========================
len is 9
free is 41
buf is [f, u, c, k, h, e, l, l, o, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ]
=====>
fuckhello
Process finished with exit code 0