Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bug: high memory usage when calling compile() #186

Closed
Mido-sys opened this issue Aug 6, 2024 · 1 comment
Closed

bug: high memory usage when calling compile() #186

Mido-sys opened this issue Aug 6, 2024 · 1 comment

Comments

@Mido-sys
Copy link
Contributor

Mido-sys commented Aug 6, 2024

Description

Description

We noticed high memory usage for this function under compiler.go: due to converting bytes to string.

func (c *compiler) compile() (string, error) {
	bb := &bytes.Buffer{}

	for _, stmt := range c.program.Statements {
		var res interface{}
		var err error

		switch node := stmt.(type) {
		case *ast.ReturnStatement:
			res, err = c.evalReturnStatement(node)

		case *ast.ExpressionStatement:
			if h, ok := node.Expression.(*ast.HTMLLiteral); ok {
				res = template.HTML(h.Value)
			} else {
				_, err = c.evalExpression(node.Expression)
			}
		case *ast.LetStatement:
			res, err = c.evalLetStatement(node)
		}

		if err != nil {
			s := stmt
			if c.curStmt != nil {
				s = c.curStmt
			}
			return "", fmt.Errorf("line %d: %w", s.T().LineNumber, err)
		}

		c.write(bb, res)
	}

	return bb.String(), nil
}

The bytes.Buffer to string conversion requires memory allocation. A better solution is to drop bytes.Buffer and just use strings.Builder instead. strings.Builder uses a more optimized code to convert to string

@Mido-sys
Copy link
Contributor Author

Mido-sys commented Aug 6, 2024

Hello @paganotoni , I pushed a fix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants