Home About

Benchmarks for 2 string libraries

It was fun reading K&R once again. Out of curiosity i set out to implement a substring search function in go. It wasn’t an easy task for a newbie programmer like me. Due to multiple frustrations i decided to peek at the go standard string library to see how it is done.

The standard strings library has a method called “Contains” that does what i need:

e.g

strings.Contains(str, subs) –> returns bool

However, i noticed that strings.Contains() calls another funciton called Index(): func Index(s, sep string) int

I immediately noticed that this function made the len(s) call 3 times. I curiosly added the following code:

m := len(s)

and replaced all 3 len(s) called with m.

Committed code can be found here: https://github.com/mesb/go/commit/5a56f4ea49b14f2251f64d7e38fbd8f892e13ac1

Thanks to some hospitable people on the #go-nuts IRC channel, i learned to do benchmarks on such experiments.

Here is the test directory: https://github.com/mesb/tests

and below are the benchmark results

Test Results

ns/op customized string lib ns/op std string lib
1308 1639
1295 1663
1307 1726
1290 1748
1246 1617
1286 1617
1261 1673
1241 1651
1312 1633
1284 1747

Average ns/op

customized lib standard lib
1283 1671.4

In effect, the golang len(string) has to be made faster.

img

Fork me on GitHub