Skip to content

Commit 19a8570

Browse files
committed
Only allocate MatchData when there is a match
Rather than letting the Ruby Garbage Collector deal with the MatchData object created that is discarded when a match is unsuccessful, only create it if we're going to return it.
1 parent 73b3ca8 commit 19a8570

File tree

1 file changed

+17
-12
lines changed

1 file changed

+17
-12
lines changed

ext/re2/re2.cc

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1521,31 +1521,36 @@ static VALUE re2_regexp_match(int argc, VALUE *argv, const VALUE self) {
15211521
/* Because match returns the whole match as well. */
15221522
n += 1;
15231523

1524-
VALUE matchdata = rb_class_new_instance(0, 0, re2_cMatchData);
1525-
TypedData_Get_Struct(matchdata, re2_matchdata, &re2_matchdata_data_type, m);
1526-
m->matches = new(std::nothrow) re2::StringPiece[n];
1527-
if (m->matches == 0) {
1524+
re2::StringPiece *matches = new(std::nothrow) re2::StringPiece[n];
1525+
if (matches == 0) {
15281526
rb_raise(rb_eNoMemError,
15291527
"not enough memory to allocate StringPieces for matches");
15301528
}
15311529

1532-
RB_OBJ_WRITE(matchdata, &m->regexp, self);
1533-
RB_OBJ_WRITE(matchdata, &m->text, rb_str_new_frozen(text));
1534-
1535-
m->number_of_matches = n;
1530+
text = rb_str_new_frozen(text);
15361531

15371532
#ifdef HAVE_ENDPOS_ARGUMENT
15381533
bool matched = p->pattern->Match(
1539-
re2::StringPiece(RSTRING_PTR(m->text), RSTRING_LEN(m->text)),
1540-
startpos, endpos, anchor, m->matches, n);
1534+
re2::StringPiece(RSTRING_PTR(text), RSTRING_LEN(text)),
1535+
startpos, endpos, anchor, matches, n);
15411536
#else
15421537
bool matched = p->pattern->Match(
1543-
re2::StringPiece(RSTRING_PTR(m->text), RSTRING_LEN(m->text)),
1544-
startpos, anchor, m->matches, n);
1538+
re2::StringPiece(RSTRING_PTR(text), RSTRING_LEN(text)),
1539+
startpos, anchor, matches, n);
15451540
#endif
15461541
if (matched) {
1542+
VALUE matchdata = rb_class_new_instance(0, 0, re2_cMatchData);
1543+
TypedData_Get_Struct(matchdata, re2_matchdata, &re2_matchdata_data_type, m);
1544+
1545+
RB_OBJ_WRITE(matchdata, &m->regexp, self);
1546+
RB_OBJ_WRITE(matchdata, &m->text, text);
1547+
m->matches = matches;
1548+
m->number_of_matches = n;
1549+
15471550
return matchdata;
15481551
} else {
1552+
delete[] matches;
1553+
15491554
return Qnil;
15501555
}
15511556
}

0 commit comments

Comments
 (0)