1

I'm trying to marshal an array into a string, separating all elements with newlines. I'm running out of memory and think about a more efficient way to do this.

buffer := "" for _, record := range all_data { body, _ := json.Marshal(record) buffer += string(body) + "\n" // i run out of memory here 

Question:

Is there a way to append a newline character to a byte array? Right now I'm casting via string(body), but I think that this operation allocates a lot of memory (but maybe I'm wrong).

4
  • How are you going to use buffer later in your app? Commented Aug 3, 2015 at 13:56
  • You can change buffer to a slice of byte and use the builtin func append(...), but if you're trying to append GB of data you can get out of memory anyway. Commented Aug 3, 2015 at 14:12
  • Consider to read stackoverflow.com/questions/24863164/… Commented Aug 3, 2015 at 14:24
  • string is constant in Golang. It's better to use bytes.Buffer instead and also other language which string is constant. Commented Aug 4, 2016 at 10:10

2 Answers 2

5

Assuming your data isn't inherently too big for the computer it's running on, the problem is likely the inefficient building of that string. Instead you should be using a bytes.buffer and then callings it's String() method. Here's an example;

var buffer bytes.Buffer for _, record := range all_data { body, _ := json.Marshal(record) buffer.Write(body) buffer.WriteString("\n") } fmt.Println(buffer.String()) 
Sign up to request clarification or add additional context in comments.

1 Comment

Heh, I was just about to post this as I just changed my code to use bytes.Buffer. Thanks!
2

To add to evanmcdonnal's answer: you don't even need an intermediate buffer created by json.Marshal:

var buf bytes.Buffer enc := json.NewEncoder(&buf) for _, record := range allData { if err := enc.Encode(record); enc != nil { // handle error } buf.WriteString("\n") // optional } fmt.Println(buf.String()) 

https://play.golang.org/p/5K9Oj0Xbjaa

1 Comment

Inside the for loop, the check should be err != nil.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.