Git Product home page Git Product logo

Comments (5)

valyala avatar valyala commented on May 18, 2024 2

The proper use case for MarshalTo is:

// The out slice is defined once and re-used multiple times
// inside the loop for marshaling different values.
var out []byte
for {
    // obtain v here
    out = v.MarshalTo(out[:0])
    // use out here
}

from fastjson.

valyala avatar valyala commented on May 18, 2024

MarshalTo must append data to the passed in slice. Just len(out) = 0 in the code above, so its' length must be extended before comparison. Try running the following code:

out := make([]byte, 0, 50000)
outNew := v.MarshalTo(out)
// Verify whether MarshalTo added data to out or put it to another memory
outExtended := out[:len(outNew)]
if bytes.Equal(outNew, outExtended) {
  log.Println("outNew points to out memory")
} else {
  log.Println("outNew points to another memory")
}

from fastjson.

valyala avatar valyala commented on May 18, 2024

See https://blog.golang.org/go-slices-usage-and-internals to understand better how slices in Go work

from fastjson.

mmacdermaid avatar mmacdermaid commented on May 18, 2024

Are you saying the proper use case for MarshalTo should then be.

out := make([]byte, 0, 50000) //or some other form of pre-allocation
out = v.MarshalTo(out)

from fastjson.

mmacdermaid avatar mmacdermaid commented on May 18, 2024

๐Ÿ‘ thanks

from fastjson.

Related Issues (20)

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.