Subject: Re: [PATCH 17/38] resolve_gitlink_ref(): avoid memory allocation in many cases

From: Junio C Hamano <[email-masked]>
Date: Tue, 07 Jun 2016 10:29:21 -0700

Michael Haggerty <[email-masked]> writes:

> If we don't have to strip trailing '/' from the submodule path, then
> don't allocate and copy the submodule name.

Makes sense.

>  int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
>  {
> -	int len = strlen(path);
> -	struct strbuf submodule = STRBUF_INIT;
> +	size_t len, orig_len = strlen(path);
>  	struct ref_store *refs;
>  	int flags;
>  
> -	while (len && path[len-1] == '/')
> -		len--;
> +	for (len = orig_len; len && path[len - 1] == '/'; len--)
> +		;
> +
>  	if (!len)
>  		return -1;
>  
> -	strbuf_add(&submodule, path, len);
> -	refs = get_ref_store(submodule.buf);
> -	strbuf_release(&submodule);
> +	if (len == orig_len) {

You can keep the original while (), without introducing orig_len,
and check if path[len] is NUL, which would probably be an end result
that is easier to read.

> +		refs = get_ref_store(path);
> +	} else {
> +		char *stripped = xmemdupz(path, len);
> +
> +		refs = get_ref_store(stripped);
> +		free(stripped);

An alternative might be to add get_ref_store_counted() that takes
(path, len) instead of NUL-terminated path, which does not look too
bad looking at the state after applying all 38 patches.

> +	}
> +
>  	if (!refs)
>  		return -1;