Skip to content

Commit eb443c9

Browse files
committed
Refactor Perl_av_fetch, optimize path for non-negative key access
1 parent c0b8ab1 commit eb443c9

File tree

1 file changed

+11
-13
lines changed

1 file changed

+11
-13
lines changed

av.c

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -266,9 +266,6 @@ S_adjust_index(pTHX_ AV *av, const MAGIC *mg, SSize_t *keyp)
266266
SV**
267267
Perl_av_fetch(pTHX_ AV *av, SSize_t key, I32 lval)
268268
{
269-
SSize_t neg;
270-
SSize_t size;
271-
272269
PERL_ARGS_ASSERT_AV_FETCH;
273270

274271
if (UNLIKELY(SvRMAGICAL(av))) {
@@ -291,24 +288,25 @@ Perl_av_fetch(pTHX_ AV *av, SSize_t key, I32 lval)
291288
}
292289
}
293290

294-
neg = (key < 0);
295-
size = AvFILLp(av) + 1;
296-
key += neg * size; /* handle negative index without using branch */
291+
SSize_t size = AvFILLp(av) + 1;
297292

298293
/* the cast from SSize_t to Size_t allows both (key < 0) and (key >= size)
299294
* to be tested as a single condition */
300295
if ((Size_t)key >= (Size_t)size) {
301-
if (UNLIKELY(neg))
296+
if (LIKELY(key < 0))
297+
key += size;
298+
else
299+
goto emptiness;
300+
301+
if (UNLIKELY(key < 0))
302302
return NULL;
303-
goto emptiness;
304303
}
305304

306-
if (!AvARRAY(av)[key]) {
307-
emptiness:
308-
return lval ? av_store(av,key,newSV_type(SVt_NULL)) : NULL;
309-
}
305+
if (AvARRAY(av)[key])
306+
return &AvARRAY(av)[key];
310307

311-
return &AvARRAY(av)[key];
308+
emptiness:
309+
return lval ? av_store(av,key,newSV_type(SVt_NULL)) : NULL;
312310
}
313311

314312
/*

0 commit comments

Comments
 (0)