最近有个小需求,校验IMEI是否为15位纯数字(是否合法),以下是正则匹配,与自己实现的简单验证方式进行压测

package main

import (
    "regexp"
    "testing"
)

func BenchmarkIsDigitalRegexp(b *testing.B) {
    for i := 0; i < b.N; i++ {
        _ = isDigitalRegexp("358901806972417")
    }
}

func BenchmarkIsDigital(b *testing.B) {
    for i := 0; i < b.N; i++ {
        _ = isDigital("358901806972417")
    }
}

func isDigitalRegexp(imei string) bool {
    if ok, _ := regexp.Match("^[0-9]{15}$", []byte(imei)); ok {
        return true
    }else {
        return false
    }
}

func isDigital(imei string) bool {
    n := len(imei)
    if n == 15 {
        for i := 0; i < n; i++ {
            if imei[i] >= 48 && imei[i] <= 57 {
                continue
            }else {
                return false
            }
        }
    }else {
        return false
    }
    return true
}

压测结果:

C:\Users\M709FJSA\go\src\pprof_demo\re>go test -bench=. -benchmem
goos: windows
goarch: amd64
pkg: pprof_demo/re
BenchmarkIsDigitalRegexp-12       300000              4644 ns/op            6450 B/op         70 allocs/op
BenchmarkIsDigital-12           200000000                9.48 ns/op            0 B/op          0 allocs/op
PASS
ok      pprof_demo/re   4.577s

很明显,正则需要重新分配内存较多,从pprof生成图也可以看出,正则调用关系错综复杂

在这里插入图片描述