Skip to content

Commit

Permalink
patch 8.2.2654: Vim9: getting a character from a string can be slow
Browse files Browse the repository at this point in the history
Problem:    Vim9: getting a character from a string can be slow.
Solution:   Avoid a function call to get the character byte size. (#8000)
  • Loading branch information
brammool committed Mar 26, 2021
1 parent 3a0f092 commit ff87140
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
2 changes: 2 additions & 0 deletions src/version.c
Expand Up @@ -750,6 +750,8 @@ static char *(features[]) =

static int included_patches[] =
{ /* Add new patch number below this line */
/**/
2654,
/**/
2653,
/**/
Expand Down
22 changes: 19 additions & 3 deletions src/vim9execute.c
Expand Up @@ -1067,21 +1067,37 @@ char_from_string(char_u *str, varnumber_T index)
return NULL;
slen = STRLEN(str);

// do the same as for a list: a negative index counts from the end
// Do the same as for a list: a negative index counts from the end.
// Optimization to check the first byte to be below 0x80 (and no composing
// character follows) makes this a lot faster.
if (index < 0)
{
int clen = 0;

for (nbyte = 0; nbyte < slen; ++clen)
nbyte += mb_ptr2len(str + nbyte);
{
if (str[nbyte] < 0x80 && str[nbyte + 1] < 0x80)
++nbyte;
else if (enc_utf8)
nbyte += utfc_ptr2len(str + nbyte);
else
nbyte += mb_ptr2len(str + nbyte);
}
nchar = clen + index;
if (nchar < 0)
// unlike list: index out of range results in empty string
return NULL;
}

for (nbyte = 0; nchar > 0 && nbyte < slen; --nchar)
nbyte += mb_ptr2len(str + nbyte);
{
if (str[nbyte] < 0x80 && str[nbyte + 1] < 0x80)
++nbyte;
else if (enc_utf8)
nbyte += utfc_ptr2len(str + nbyte);
else
nbyte += mb_ptr2len(str + nbyte);
}
if (nbyte >= slen)
return NULL;
return vim_strnsave(str + nbyte, mb_ptr2len(str + nbyte));
Expand Down

0 comments on commit ff87140

Please sign in to comment.