powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Firebird, InterBase [игнор отключен] [закрыт для гостей] / where s LIKE '%txt%' *vs* where s NOT like '%txt%': первое быстрее. Why ?
9 сообщений из 84, страница 4 из 4
where s LIKE '%txt%' *vs* where s NOT like '%txt%': первое быстрее. Why ?
    #38514981
Таблоид
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
dimitrПиши трекеру, авось Адриано сподобится этим заняться. Поздравил я его с НГ, пущай почитает.
ЗЫ. Решил сравнить с Большим Братом.
Результат: если строка *И* шаблон объявлены одинаковым образом, то всё пучком, как для varchar2 так и для N varchar2.
0.5 sec
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
SH@ao61 14:26:01>declare
  2    n number := 10000000;
  3    s nvarchar2(32000 char);
  4    p nvarchar2(3 char) := '%q%';
  5    --s varchar2(32000);
  6    --p varchar2(3) := '%q%';
  7    cnt number := 0;
  8  begin
  9    s:=rpad('q', 16000);
 10    for i in 1..n loop
 11      if s like p then
 12        cnt := cnt+1;
 13       end if;
 14    end loop;
 15    dbms_output.put_line(cnt);
 16  end;
 17  /
10000000

Elapsed: 00:00:00.51

Но когда строка объявлена как N varchar2, а шаблон не объявлен вообще, а просто указан в LIKE-операторе, то у них там тупить что-то начинает:
90 sec!
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
SH@ao61 14:04:32>declare
  2    n number := 10000000;
  3    s nvarchar2(4000);
  4    cnt number := 0;
  5  begin
  6    s:=rpad('q', 4000);
  7    for i in 1..n loop
  8      if s like '%q%' then
  9        cnt := cnt+1;
 10       end if;
 11    end loop;
 12    dbms_output.put_line(cnt);
 13  end;
 14  /
10000000

PL/SQL procedure successfully completed.

Elapsed: 00:01:29.90


У нас же ситуация лучше: такой дикой разницы нет.
Если объявить строку *И* шаблон как utf8, то на длине 50 будет:
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
set stat on;
set term ^;
execute block returns(cnt int) as
declare n int = 10000000;
declare s varchar(50) character set utf8;
declare p varchar(3) character set utf8;
begin
cnt=0;
s=rpad('q',50,' ');
 p ='%q%';
while (n>0) do begin
  cnt = cnt + iif( s like  p , 1, 0);
  n=n-1;
end
  suspend;
end^
set term ;^
set stat off;
Код: plaintext
Elapsed time= 16.22 sec

А если шаблон просто подсовывать в явном виде:
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
set stat on;
set term ^;
execute block returns(cnt int) as
declare n int = 10000000;
declare s varchar(50) character set utf8;
--declare p varchar(3) character set utf8;
begin
cnt=0;
s=rpad('q',50,' ');
--p='%q%';
while (n>0) do begin
  cnt = cnt + iif( s like  '%q%' , 1, 0);
  n=n-1;
end
  suspend;
end^
set term ;^
set stat off;
- то:
Код: plaintext
Elapsed time= 14.20 sec
...
Рейтинг: 0 / 0
where s LIKE '%txt%' *vs* where s NOT like '%txt%': первое быстрее. Why ?
    #38514985
Таблоид
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Dimitry SibiryakovТаблоидон же того, регистроЧувственный как раз.
Даже если выставить CI-коллейт?..Если указывать явно - да, будет case INsensitive:

Код: plaintext
1.
2.
3.
4.
5.
SQL> with c as (select _utf8 'эхо мацы' s1, _utf8 'Эхо Мацы' s2 from rdb$database)
CON> select s1,s2,iif(s1 collate unicode_ci like s2 collate unicode_ci, 1, 0) r from c;

S1       S2                  R
======== ======== ============
эхо мацы Эхо Мацы            1

Но для этого же containing есть.
...
Рейтинг: 0 / 0
where s LIKE '%txt%' *vs* where s NOT like '%txt%': первое быстрее. Why ?
    #38515412
Basil A. Sidorov
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
ТаблоидРешил проверить, что там на яве будет в аналогичном случае (NB: такой же интерпретируемый языкУ тебя совесть есть?
Большие киты уже второе тысячелетие пилят "оперативную компиляцию" (just-in-time compiler), а ты - "интерпретируемый".
Сравни с ключом "-int", если уж так хочется потрепаться за интерпретацию.
...
Рейтинг: 0 / 0
where s LIKE '%txt%' *vs* where s NOT like '%txt%': первое быстрее. Why ?
    #38515423
Таблоид
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Basil A. SidorovТаблоидРешил проверить, что там на яве будет в аналогичном случае (NB: такой же интерпретируемый языкУ тебя совесть есть?
Большие киты уже второе тысячелетие пилят "оперативную компиляцию" (just-in-time compiler), а ты - "интерпретируемый".
Сравни с ключом "-int", если уж так хочется потрепаться за интерпретацию.Давай сюда версию своей явы, обе команды (компиляция + запуск) и результаты для коротких и длинных строк - так, как я выше привёл.
У меня такого ключика нет. Вообще.
javac -help
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
Usage: javac <options> <source files>
where possible options include:
  -g                         Generate all debugging info
  -g:none                    Generate no debugging info
  -g:{lines,vars,source}     Generate only some debugging info
  -nowarn                    Generate no warnings
  -verbose                   Output messages about what the compiler is doing
  -deprecation               Output source locations where deprecated APIs are used
  -classpath <path>          Specify where to find user class files and annotation processors
  -cp <path>                 Specify where to find user class files and annotation processors
  -sourcepath <path>         Specify where to find input source files
  -bootclasspath <path>      Override location of bootstrap class files
  -extdirs <dirs>            Override location of installed extensions
  -endorseddirs <dirs>       Override location of endorsed standards path
  -proc:{none,only}          Control whether annotation processing and/or compilation is done.
  -processor <class1>[,<class2>,<class3>...]Names of the annotation processors to run; bypasses default discovery process
  -processorpath <path>      Specify where to find annotation processors
  -d <directory>             Specify where to place generated class files
  -s <directory>             Specify where to place generated source files
  -implicit:{none,class}     Specify whether or not to generate class files for implicitly referenced files 
  -encoding <encoding>       Specify character encoding used by source files
  -source <release>          Provide source compatibility with specified release
  -target <release>          Generate class files for specific VM version
  -version                   Version information
  -help                      Print a synopsis of standard options
  -Akey[=value]              Options to pass to annotation processors
  -X                         Print a synopsis of nonstandard options
  -J<flag>                   Pass <flag> directly to the runtime system
java -help
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
Usage: java [-options] class [args...]
           (to execute a class)
   or  java [-options] -jar jarfile [args...]
           (to execute a jar file)

where options include:
    -client       to select the "client" VM
    -server       to select the "server" VM
    -hotspot      is a synonym for the "client" VM  [deprecated]
                  The default VM is client.
                  
    -cp <class search path of directories and zip/jar files>
    -classpath <class search path of directories and zip/jar files>
                  A ; separated list of directories, JAR archives,
                  and ZIP archives to search for class files.
    -D<name>=<value>
                  set a system property
    -verbose[:class|gc|jni]
                  enable verbose output
    -version      print product version and exit
    -version:<value>
                  require the specified version to run
    -showversion  print product version and continue
    -jre-restrict-search | -jre-no-restrict-search
                  include/exclude user private JREs in the version search
    -? -help      print this help message
    -X            print help on non-standard options
    -ea[:<packagename>...|:<classname>]
    -enableassertions[:<packagename>...|:<classname>]
                  enable assertions
    -da[:<packagename>...|:<classname>]
    -disableassertions[:<packagename>...|:<classname>]
                  disable assertions
    -esa | -enablesystemassertions
                  enable system assertions
    -dsa | -disablesystemassertions
                  disable system assertions
    -agentlib:<libname>[=<options>]
                  load native agent library <libname>, e.g. -agentlib:hprof
                    see also, -agentlib:jdwp=help and -agentlib:hprof=help
    -agentpath:<pathname>[=<options>]
                  load native agent library by full pathname
    -javaagent:<jarpath>[=<options>]
                  load Java programming language agent, see java.lang.instrument
    -splash:<imagepath>
                  show splash screen with specified image
...
Рейтинг: 0 / 0
where s LIKE '%txt%' *vs* where s NOT like '%txt%': первое быстрее. Why ?
    #38515425
Basil A. Sidorov
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
    -Xmixed           mixed mode execution (default)
   -Xint             interpreted mode execution only
    -Xbootclasspath:<directories and zip/jar files separated by ;>
                      set search path for bootstrap classes and resources
    -Xbootclasspath/a:<directories and zip/jar files separated by ;>
                      append to end of bootstrap class path
    -Xbootclasspath/p:<directories and zip/jar files separated by ;>
                      prepend in front of bootstrap class path
    -Xnoclassgc       disable class garbage collection
    -Xincgc           enable incremental garbage collection
    -Xloggc:<file>    log GC status to a file with time stamps
    -Xbatch           disable background compilation
    -Xms<size>        set initial Java heap size
    -Xmx<size>        set maximum Java heap size
    -Xss<size>        set java thread stack size
    -Xprof            output cpu profiling data
    -Xfuture          enable strictest checks, anticipating future default
    -Xrs              reduce use of OS signals by Java/VM (see documentation)
    -Xcheck:jni       perform additional checks for JNI functions
    -Xshare:off	      do not attempt to use shared class data
    -Xshare:auto      use shared class data if possible (default)
    -Xshare:on	      require using shared class data, otherwise fail.

The -X options are non-standard and subject to change without notice.

Плюс, надо учитывать, что JIT тоже требует времени "на раскочегариться".
Поэтому рекомендуется сначала покрутить тестируемый код секунду-другую и только потом начинать замеры.
...
Рейтинг: 0 / 0
where s LIKE '%txt%' *vs* where s NOT like '%txt%': первое быстрее. Why ?
    #38515491
Таблоид
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Basil A. Sidorov,

чё-то ты мне не то подсказал :-)

Сначала я думкал, что всё взвисло (ЦПУ на 99%), но затем вылезло:
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
java -Xint MatchesCount
s.length()=32760, cnt=10000000, done at 93266 ms

java -Xint MatchesCount 10
s.length()=10, cnt=10000000, done at 103203 ms

java -Xint MatchesCount 10
s.length()=10, cnt=10000000, done at 97454 ms

Значение несопоставимо ни с какими воротами, замедлитель какой-то туда всунули. Фтопку его.
Тем более, что Адриано уже взял в разработку этот тикет.
...
Рейтинг: 0 / 0
where s LIKE '%txt%' *vs* where s NOT like '%txt%': первое быстрее. Why ?
    #38516040
Basil A. Sidorov
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
ТаблоидBasil A. Sidorov,
чё-то ты мне не то подсказал :-)Было заявлено, что ява - интерпретируемый язык.
Теперь тебе известна разница между интерпретацией (-Xint) и компиляцией (-Xmixed, по умолчанию).
...
Рейтинг: 0 / 0
where s LIKE '%txt%' *vs* where s NOT like '%txt%': первое быстрее. Why ?
    #38525272
Cobalt747
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Таблоид,

Велика ли разница по времени между выборкой всех строк и выборкой по шаблону?
...
Рейтинг: 0 / 0
where s LIKE '%txt%' *vs* where s NOT like '%txt%': первое быстрее. Why ?
    #38525486
Таблоид
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Cobalt747Велика ли разница по времени между выборкой всех строк и выборкой по шаблону?а что даст это сравнение ?
...
Рейтинг: 0 / 0
9 сообщений из 84, страница 4 из 4
Форумы / Firebird, InterBase [игнор отключен] [закрыт для гостей] / where s LIKE '%txt%' *vs* where s NOT like '%txt%': первое быстрее. Why ?
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]