且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ruby直接字符串压缩与解压缩

更新时间:2022-06-29 00:47:46

    ruby2.1.3的核心类中包含了Zlib库,其中的Zlib模块包含了对字符串压缩和解压的方法:

irb(main):180:0> Zlib.class
=> Module
irb(main):181:0> Zlib.constants
=> [:Error, :StreamEnd, :NeedDict, :DataError, :StreamError, :MemError, :BufError, :VersionError, :VERSION, :ZLIB_VERSION, :ZStream, :BINARY, :ASCII, :TEXT, 
:UNKNOWN, :Deflate, :Inflate, :NO_COMPRESSION, :BEST_SPEED, :BEST_COMPRESSION, :DEFAULT_COMPRESSION, :FILTERED, :HUFFMAN_ONLY, :RLE, :FIXED, 
:DEFAULT_STRATEGY, :MAX_WBITS, :DEF_MEM_LEVEL, :MAX_MEM_LEVEL, :NO_FLUSH, :SYNC_FLUSH, :FULL_FLUSH, :FINISH, :GzipFile, :GzipWriter, :GzipReader, 
:OS_CODE, :OS_MSDOS, :OS_AMIGA, :OS_VMS, :OS_UNIX, :OS_ATARI, :OS_OS2, :OS_MACOS, :OS_TOPS20, :OS_WIN32, :OS_VMCMS, :OS_ZSYSTEM, :OS_CPM,
 :OS_QDOS, :OS_RISCOS, :OS_UNKNOWN]

我们写一段简单的代码测试下:

#!/usr/bin/ruby

require 'zlib'
include Zlib

def sh_size(str)
	puts "string size is #{str.size}"
end

def calc(start,&b)
	zstr = b.call
	puts "take %f s" % (Time.now - start)
	sh_size(zstr)
	zstr
end

def zip(str,mode=DEFAULT_COMPRESSION)
	printf("Test Mode:#{mode} : ")
	calc(Time.now)  do
		Deflate.deflate(str,mode)
	end
end

def unzip(zstr)
	Inflate.inflate(zstr)
end

str = (('a'..'z').to_a + ('0'..'9').to_a).shuffle.join('') * 1000000
puts "org_str size is #{str.size}"

zip(str,BEST_SPEED)
zip(str)
zstr = zip(str,BEST_COMPRESSION)

sh_size unzip(zstr)

运行结果如下:

wisy@wisy-ThinkPad-X61:~/src/ruby_src$ ./fk.rb
org_str size is 36000000
Test Mode:1 : take 0.255531 s
string size is 192037
Test Mode:-1 : take 0.497991 s
string size is 104822
Test Mode:9 : take 0.539890 s
string size is 104822
string size is 36000000

不如把所有压缩级别都试一下吧:

-1.upto(9) {|x| zip(str,x)}

最后结果如下,感觉很多级别都差不多啊:

org_str size is 36000000
Test Mode:-1 : take 0.433412 s
string size is 104821
Test Mode:0 : take 0.383851 s
string size is 36005496
Test Mode:1 : take 0.254758 s
string size is 192036
Test Mode:2 : take 0.264866 s
string size is 192036
Test Mode:3 : take 0.254311 s
string size is 192036
Test Mode:4 : take 0.438662 s
string size is 104821
Test Mode:5 : take 0.429670 s
string size is 104821
Test Mode:6 : take 0.439067 s
string size is 104821
Test Mode:7 : take 0.435192 s
string size is 104821
Test Mode:8 : take 0.444039 s
string size is 104821
Test Mode:9 : take 0.453219 s
string size is 104821