Which "out. Close" is Better?

Hi there

Which “out. Close” good performance for language? (as u know “defer” not good in for)

1 .

func SaveAvatar() string{
	var size [6][2]uint
	    size[0] = [2]uint{75, 30}
	    size[1] = [2]uint{100, 40}

	for _, v := range size {
		out, err := os.Create("pic/ava/" + "u" + "_" +
			"150000" + "_" + "123" + "_" + strconv.Itoa(int(v[0])) + "." +"JPG")
		if err != nil {
			return "R_FAILED"
		}
		//jpeg.Encode(out, Avatar, nil)

		err =os.Remove("Av" + "_" + strconv.Itoa(int(v[0])) + "." + "JPG")
		if err != nil {
			return "R_FAILED"
		}
		out.Close()
	}
	return "R_Succ"
}
func SaveAvatar() string{
	var size [6][2]uint
	    size[0] = [2]uint{75, 30}
	    size[1] = [2]uint{100, 40}

	for _, v := range size {
		out, err := os.Create("pic/ava/" + "u" + "_" +
			"150000" + "_" + "123" + "_" + strconv.Itoa(int(v[0])) + "." +"JPG")
		if err != nil {
		out.Close()
			return "R_FAILED"
		}
		//jpeg.Encode(out, Avatar, nil)

		err =os.Remove("Av" + "_" + strconv.Itoa(int(v[0])) + "." + "JPG")
		if err != nil {
		out.Close()
			return "R_FAILED"
		}
		out.Close()
	}
	return "R_Succ"
}

here is playGround :

https://play.golang.org/p/49u1nJYi8xU

Thanks in Advance.

See this discussion. Wrapping it in an anonymous function could be a solution

2 Likes

Hi Hamed,

Two things:

  1. If the open (or create) fails, then there is no file to close. You do not have to call out.Close() because out is nil.

  2. You just need to close the file after you are done using it. So put your os.Close() immediately after the jpeg.Encode().

Try this: https://play.golang.org/p/8W9ezx4UBTf

2 Likes
out, err := os.Create("pic/ava/" + "u" + "_" + "150000" + "_" + "123" + "_" + strconv.Itoa(int(v[0])) + "." +"JPG")

Could be rewritten as

out, err := os.Create(fmt.Sprintf("pic/ava/u150000_123_%s.JPG", v[0]))

which is a little shorter and it is easier to see what path is used for os.Create. Same thing with the argument to os.Unlink

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.