Skip to content

Redundant Buffer Allocation & Copy #2736

Open
@jfcg

Description

@jfcg

Hi,
Please see the discussion here. This piece of code:

package main

import (
	"fmt"
	"unsafe"
)

// ToLower converts ascii string s to lower-case
func ToLower(s string) string {
	if s == "" {
		return ""
	}
	buf := make([]byte, len(s))
	fmt.Println(unsafe.Pointer(&buf[0])) // just to identify buffer

	for i := 0; i < len(s); i++ {
		c := s[i]
		if 'A' <= c && c <= 'Z' {
			c |= 32
		}
		buf[i] = c
	}
	return string(buf)
}

func main() {
	s := ToLower("ASfgQW")

	fmt.Println(*(*unsafe.Pointer)(unsafe.Pointer(&s)))
}

shows that both Go and TinyGo compilers fail to detect that buf does not escape, can just be converted to a string and returned. Instead both compilers redundantly allocate a new buffer and copy bytes in return string(buf).

How can this be solved in TinyGo?

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions