From 63638fd271315e4df813bd65c716688a3431efca Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Mon, 28 Jun 2021 17:45:04 +0300 Subject: [PATCH] cgen: optimize generated array.index(elem) --- vlib/builtin/array.v | 1 + vlib/v/gen/c/array.v | 15 ++++++++------- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/vlib/builtin/array.v b/vlib/builtin/array.v index e754b1eb1c..740aeabd70 100644 --- a/vlib/builtin/array.v +++ b/vlib/builtin/array.v @@ -568,6 +568,7 @@ pub fn (mut a []int) sort() { // index returns the first index at which a given element can be found in the array // or -1 if the value is not found. +[direct_array_access] pub fn (a []string) index(v string) int { for i in 0 .. a.len { if a[i] == v { diff --git a/vlib/v/gen/c/array.v b/vlib/v/gen/c/array.v index 62cab8fced..df82dd2f12 100644 --- a/vlib/v/gen/c/array.v +++ b/vlib/v/gen/c/array.v @@ -536,22 +536,23 @@ fn (mut g Gen) gen_array_index_method(left_type ast.Type) string { g.type_definitions.writeln('static int ${fn_name}($left_type_str a, $elem_type_str v); // auto') mut fn_builder := strings.new_builder(512) fn_builder.writeln('static int ${fn_name}($left_type_str a, $elem_type_str v) {') - fn_builder.writeln('\tfor (int i = 0; i < a.len; ++i) {') + fn_builder.writeln('\t$elem_type_str* pelem = a.data;') + fn_builder.writeln('\tfor (int i = 0; i < a.len; ++i, ++pelem) {') if elem_sym.kind == .string { - fn_builder.writeln('\t\tif (fast_string_eq(((string*)a.data)[i], v)) {') + fn_builder.writeln('\t\tif (fast_string_eq(( *pelem, v))) {') } else if elem_sym.kind == .array && !info.elem_type.is_ptr() { ptr_typ := g.gen_array_equality_fn(info.elem_type) - fn_builder.writeln('\t\tif (${ptr_typ}_arr_eq((($elem_type_str*)a.data)[i], v)) {') + fn_builder.writeln('\t\tif (${ptr_typ}_arr_eq( *pelem, v)) {') } else if elem_sym.kind == .function && !info.elem_type.is_ptr() { - fn_builder.writeln('\t\tif (((voidptr*)a.data)[i] == v) {') + fn_builder.writeln('\t\tif ( pelem == v) {') } else if elem_sym.kind == .map && !info.elem_type.is_ptr() { ptr_typ := g.gen_map_equality_fn(info.elem_type) - fn_builder.writeln('\t\tif (${ptr_typ}_map_eq((($elem_type_str*)a.data)[i], v)) {') + fn_builder.writeln('\t\tif (${ptr_typ}_map_eq(( *pelem, v))) {') } else if elem_sym.kind == .struct_ && !info.elem_type.is_ptr() { ptr_typ := g.gen_struct_equality_fn(info.elem_type) - fn_builder.writeln('\t\tif (${ptr_typ}_struct_eq((($elem_type_str*)a.data)[i], v)) {') + fn_builder.writeln('\t\tif (${ptr_typ}_struct_eq( *pelem, v)) {') } else { - fn_builder.writeln('\t\tif ((($elem_type_str*)a.data)[i] == v) {') + fn_builder.writeln('\t\tif (*pelem == v) {') } fn_builder.writeln('\t\t\treturn i;') fn_builder.writeln('\t\t}')