当前位置:网站首页>用位运算为你的程序加速
用位运算为你的程序加速
2022-08-02 01:48:00 【crossoverJie】
前言
最近在持续优化之前编写的 JSON
解析库 xjson,主要是两个方面的优化。
第一个是支持将一个 JSONObject
对象输出为 JSON
字符串。
这点在上个版本中只是利用自带的 Print
函数打印数据:
func TestJson4(t *testing.T) { str := `{"people":{"name":{"first":"bob"}}}` first := xjson.Get(str, "people.name.first") assert.Equal(t, first.String(), "bob") get := xjson.Get(str, "people") fmt.Println(get.String()) //assert.Equal(t, get.String(),`{"name":{"first":"bob"}}`)}
Output:
map[name:map[first:bob]]
<!--more-->
本次优化之后便能直接输出 JSON 字符串了:
实现过程也很简单,只需要递归遍历 object 中的数据,然后拼接字符串即可,核心代码如下:
func (r Result) String() string { switch r.Token { case String: return fmt.Sprint(r.object) case Bool: return fmt.Sprint(r.object) case Number: i, _ := strconv.Atoi(fmt.Sprint(r.object)) return fmt.Sprintf("%d", i) case Float: i, _ := strconv.ParseFloat(fmt.Sprint(r.object), 64) return fmt.Sprintf("%f", i) case JSONObject: return object2JSONString(r.object) case ArrayObject: return object2JSONString(r.Array()) default: return "" }}
用位运算优化
第二个优化主要是提高了性能,查询一个复杂 JSON 数据的时候性能提高了大约 16%.
# 优化前BenchmarkDecode-12 90013 66905 ns/op 42512 B/op 1446 allocs/op# 优化后BenchmarkDecode-12 104746 59766 ns/op 37749 B/op 1141 allocs/op
这里截取了一些重点改动的部分:
在 JSON 解析过程中会有一个有限状态机状态迁移的过程,而迁移的时候可能会出现多个状态。
比如当前解析到的 token 值为 {
,那它接下来的 token 可能会为 ObjectKey:"name"
,也可能会是 BeginObject:{
,当然也可能会是 EndObject:}
, 所以在优化之前我是将状态全部存放在一个集合中的,在解析过程中如果发现状态不满足预期的列表时则会抛出语法异常的错误。
所以优化之前是遍历这个集合来进行判断的,这样的时间复杂度为 O(N)
,但当我们换成位运算就不一样了,时间复杂度直接就变为O(1)
了,同时还节省了一个切片的存储空间。
我们简单来分析下这个位运算为什么会达到判断一个数据是否在一个集合中同样的效果。
首先以这两个状态为例:
StatusObjectKey status = 0x0002 StatusColon status = 0x0004
他们分别对应的二进制数据为:
StatusObjectKey status = 0x0002 //0010 StatusColon status = 0x0004 //0100
当我们对这两个数据求 |
运算得到的数据是 0110
:
A:0010B:0100C:0110
这时候如何我们如果用这两个原始数据与 C:0110
做 &
运算时就会还原为刚才的两个数据。
// input:A:0010C:0110// output:A:0010----------// input:B:0100C:0110// output:B:0100
但我们换一个 D 与 C 求 &
时:
D: 1000 // 0x0008 对应的二进制为 1000C: 0110D':0000
将会得到一个 0 值,只要得出的数据大于 0 我们就能判断一个数据是否在给定的集合中了。
> 当然这里有一个前提条件就是,我们输入的数据高位永远都是是 1 才行,也就是2的幂。
同样的优化在解析查询语法时也有使用:
其他奇淫巧技
当然位运算还有一些其他技巧,比如判断奇偶数:
// 偶数a & 1 == 0// 奇数a & 1 == 1
乘法和除法,右移1一位是除以2,左移一位是乘以2.
x := 2fmt.Println(x>>1) //1fmt.Println(x<<1) //4
总结
位运算在带来程序性能提升的同时也降低代码可读性,所以我们得按需选择是否使用;
再一些底层库、框架代码对性能有极致追求的场景推荐使用,但在业务代码中对数据做加减乘除就没必要用位运算了,只会让后续的维护者一脸懵逼。
边栏推荐
- YGG 公会发展计划第 1 季总结
- Day116.尚医通:预约挂号详情 ※
- 秒懂大模型 | 3步搞定AI写摘要
- C语言之插入字符简单练习
- 信息化和数字化的本质区别是什么?
- Entry name ‘org/apache/commons/codec/language/bm/gen_approx_greeklatin.txt’ collided
- Shell Beginners Final Chapter
- 传统企业数字化转型需要经过几个阶段?
- MySQL——增删查改操作
- Can't connect to MySQL server on 'localhost3306' (10061) Simple and clear solution
猜你喜欢
6-25漏洞利用-irc后门利用
The Paddle Open Source Community Quarterly Report is here, everything you want to know is here
Constructor of typescript35-class
LeetCode刷题日记:74. 搜索二维矩阵
Reflex WMS中阶系列6:对一个装货重复run pick会有什么后果?
超大规模的产业实用语义分割数据集PSSL与预训练模型开源啦!
Use flex-wrap to wrap lines in flex layout
Some insights from 5 years of automated testing experience: UI automation must overcome these 10 pits
3 Month Tester Readme: 4 Important Skills That Impacted My Career
Can't connect to MySQL server on 'localhost3306' (10061) Simple and clear solution
随机推荐
6-24漏洞利用-vnc密码破解
Flask gets post request parameters
Day115. Shangyitong: Background user management: user lock and unlock, details, authentication list approval
LeetCode刷题日记:LCP 03.机器人大冒险
typescript33-typescript高级概述
垃圾回收器CMS和G1
Multi-Party Threshold Private Set Intersection with Sublinear Communication-2021: Interpretation
MySQL——增删查改操作
Use baidu EasyDL implement factory workers smoking behavior recognition
手写一个博客平台~第一天
编码经验之谈
HSDC is related to Independent Spanning Tree
Can't connect to MySQL server on 'localhost3306' (10061) Simple and clear solution
Kubernetes之本地存储
About MySQL data insertion (advanced usage)
Constructor of typescript35-class
MySQL optimization strategy
3. Bean scope and life cycle
After graduating from three books, I was rejected by Tencent 14 times, and finally successfully joined Alibaba
Record the pits where an error occurs when an array is converted to a collection, and try to use an array of packaging types for conversion