2 ms·
> Go knows that doPerson can't modify person so it is free to allocate the variable on the stack Escape analysis does not care about modification. It only care
by arghwhat 8y ago
> Go knows that doPerson can't modify person so it is free to allocate the variable on the stack
Escape analysis does not care about modification. It only cares about whether the scope of the variable may end up expanded past the end of the function. Whether that scope is read or write is not relevant.
Causes of escape would be returning the value from the function, referencing the value in a closure, or using a reference to the value in a context with a different lifetime (channels, structs outliving the function). Calling a function with an argument as reference is not a cause of escape.
Escape analysis is tricky and fragile. Go often has to bail out to the heap.
Also, you don't really pass around structs by value much in real code, so the point that this is a benefit to GC performance is kind of moot.
- bjourne 8y agoTrue! What matters is that doPerson() doesn't get hold of a reference to the object which could cause escape. Since it doesn't get hold of a reference, it of course can't modify the object either. Had the call been doPerson(&person) it would have gotten a reference and Go would be forced to heap-allocate person. I agree that escape analysis is tricky because it is easier than one might think for objects to escape. That Go is better than Java at imprisoning objects I think is mostly because of different usage patterns between programmers of the two languages.