Giter Club home page Giter Club logo

itoalen_godemo's Introduction

Itoa Length

This is a quick test on the best way to find the string length of an itoa output.

Our base line is ItoalenWithItoa, e.g. len(strconv.Itoa(123)). This is the worst we can do: not only is performance O(n), there is also allocation per call.

Using log (ItoalenWithLog) is a lot better. At least we're getting O(1).

Repeated multiplication (ItoalenWithMul) beats using log, although we're back to being O(n). I tried using bit shift (ItoalenWithMul2), with exactly the same performance. Looks like Go compiler has optimized this away already.

The fastest algo I found that is still elegant is division by 2 (ItoalenWithDiv2). It's basically O(1), or at least a very gradual O(n) slope. It's also faster than all the above.

The actual winner is, unsurprisingly, just old plain if...else branching. It's ugly but...yeah it works.

Benchmark

Benchmark script

Create log:

GO111MODULE=off go test -v -bench=. > bench_result.log

Massage into csv, then paste into Excel:

Get-Clipboard | where { $_ -like "*-2*" } | % { 
    $funcName = $_.Split(' ')[0].Split('/')[0].Substring('BenchmarkItoalenWith'.Length)
    $intlen = $_.Split(' ')[0].Split('/')[1].Substring('intlen_'.Length).Split('-')[0]
    $speed =  $_.Substring($_.LastIndexOf('  ')).Trim().Split(' ')[0]

    '{0},{1},{2}' -f $funcName, $intlen, $speed
}

itoalen_godemo's People

Contributors

imacks avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.