background image

十进制数据压缩的试验

简介

ERP 应用中,经常要将大批量的数据下载到客户端本地,例如查询、报表或导出等功能,

这将消耗大量的网络资源来传输数据,特别是在移动办公时,较大的数据量将造成等待时
间太长。本文以压缩十进制数据为例描述了压缩这些数据的实践。

分析案例

在传输的数据中,有各种类型的数据,有字符串、时间、十进制或

bool 等,本文将分析十进

制这种类型。

.net 中,decimal 是一个可以描述较大数据和小数,且保证计算准确的数据类型,比较适

ERP 应用,但是他占用的空间比较大,反编译其申明可以看到其占用 4 个 int32,即高达

16 个字节。

1

     

private

 

int

 flags;

2

     

private

 

int

 hi;

3

     

private

 

int

 lo;

4

     

private

 

int

 mid;

直接调用

GetBits(Decimal) : Int32[]

存储显然不合算。

参考实现

微软内部是如何存储的呢?

System.IO.BinaryWriter

的默认实现还真的是这么干的,请看:

1

 

public

 

virtual

 

void

 Write(

decimal

 value)

2

 {

3

     

decimal

.GetBytes(value, 

this

._buffer);

4

     

this

.OutStream.Write(

this

._buffer, 

0

0x10

);

5

 }

:不过他有点耍赖,调用了 internal 的 GetBytes 减少了 byte[]数组的不断创建。

在二进制序列化的实现

System.Runtime.Serialization.Formatters.Binary.__BinaryWriter 中,使

用了较为巧妙的方法

,他将其转换为字符串存储:

1

 

internal

 

void

 WriteDecimal(

decimal

 value)

2

 {