@@ -1595,10 +1595,11 @@ S_parse_gv_stash_name(pTHX_ HV **stash, GV **gv, const char **name,
1595
1595
STRLEN * len , const char * nambeg , STRLEN full_len ,
1596
1596
const U32 is_utf8 , const I32 add )
1597
1597
{
1598
- char * tmpbuf = NULL ;
1598
+ char * tmpfullbuf = NULL ; /* only malloc one big chunk of memory when the smallbuff is not large enough */
1599
1599
const char * name_cursor ;
1600
1600
const char * const name_end = nambeg + full_len ;
1601
1601
const char * const name_em1 = name_end - 1 ;
1602
+ char smallbuf [64 ]; /* small buffer to avoid a malloc when possible */
1602
1603
1603
1604
PERL_ARGS_ASSERT_PARSE_GV_STASH_NAME ;
1604
1605
@@ -1629,8 +1630,16 @@ S_parse_gv_stash_name(pTHX_ HV **stash, GV **gv, const char **name,
1629
1630
* len += 2 ;
1630
1631
}
1631
1632
else { /* using ' for package separator */
1632
- if (tmpbuf == NULL ) /* only malloc&free once, a little more than needed */
1633
- Newx (tmpbuf , full_len + 2 , char );
1633
+ /* use our pre-allocated buffer when possible to save a malloc */
1634
+ char * tmpbuf ;
1635
+ if ( * len + 2 <= sizeof smallbuf )
1636
+ tmpbuf = smallbuf ;
1637
+ else {
1638
+ /* only malloc once if needed */
1639
+ if (tmpfullbuf == NULL ) /* only malloc&free once, a little more than needed */
1640
+ Newx (tmpfullbuf , full_len + 2 , char );
1641
+ tmpbuf = tmpfullbuf ;
1642
+ }
1634
1643
Copy (* name , tmpbuf , * len , char );
1635
1644
tmpbuf [(* len )++ ] = ':' ;
1636
1645
tmpbuf [(* len )++ ] = ':' ;
@@ -1639,7 +1648,7 @@ S_parse_gv_stash_name(pTHX_ HV **stash, GV **gv, const char **name,
1639
1648
gvp = (GV * * )hv_fetch (* stash , key , is_utf8 ? - ((I32 )* len ) : (I32 )* len , add );
1640
1649
* gv = gvp ? * gvp : NULL ;
1641
1650
if (!* gv || * gv == (const GV * )& PL_sv_undef ) {
1642
- Safefree (tmpbuf );
1651
+ Safefree (tmpfullbuf ); /* free our tmpfullbuf if it was used */
1643
1652
return FALSE;
1644
1653
}
1645
1654
/* here we know that *gv && *gv != &PL_sv_undef */
@@ -1681,7 +1690,7 @@ S_parse_gv_stash_name(pTHX_ HV **stash, GV **gv, const char **name,
1681
1690
MUTABLE_HV (SvREFCNT_inc_simple (PL_defstash ));
1682
1691
}
1683
1692
}
1684
- Safefree (tmpbuf );
1693
+ Safefree (tmpfullbuf ); /* free our tmpfullbuf if it was used */
1685
1694
return TRUE;
1686
1695
}
1687
1696
}
0 commit comments